2

I have a data frame and I want to create a new variable applying a function that works within rows. See the example below.

library(tidyverse)

n <- 100
z0 <- data.frame(A = sample(c("y","n",NA), n, replace = T, prob = c(.4,.4,.1)),
                 B = sample(c("y","n",NA), n, replace = T, prob = c(.4,.4,.1)),
                 C = sample(c("y","n",NA), n, replace = T, prob = c(.4,.4,.1)))

z0 %>% apply(1, function(x) any("y" == x)) -> z0$new
summary(z0)

I would want to do it with mutate but I have fail. I appreciate any suggestions.

2
  • Do you want new to equal TRUE if any columns A:C == y?
    – CPak
    Apr 18, 2018 at 15:01
  • that is correct Apr 18, 2018 at 15:03

2 Answers 2

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

2

Here's a tidyverse approach. Let's create a data frame with all the possibilities to make sure nothing gets missed.

library(tidyverse)
(z0 <- data_frame(A = c("y", "n", NA, NA, NA), 
                 B = c("n", "n", "y", "n", NA), 
                 C = c("n", "n", "n", "n", NA)))
#> # A tibble: 5 x 3
#>   A     B     C    
#>   <chr> <chr> <chr>
#> 1 y     n     n    
#> 2 n     n     n    
#> 3 <NA>  y     n    
#> 4 <NA>  n     n    
#> 5 <NA>  <NA>  <NA>

Here's a safe approach using purrr::pmap_lgl that requires you to explicitly put in which variables you want to include to see where "y" might appear:

z0 %>% 
  mutate(new = pmap_lgl(., ~ any("y" == c(..1, ..2, ..3))))

Here's an approach using purrrlyr (a small package with some functions orphaned from purrr) which has the benefit of using ... to indicate all variables:

z0 %>% 
  purrrlyr::by_row(~ any("y" == ...), .collate = "rows", .to = "new")

Both give the same result:

#> # tibble [5 × 4]
#>   A     B     C     new
#>   <chr> <chr> <chr> <lgl>  
#> 1 y     n     n     TRUE   
#> 2 n     n     n     FALSE  
#> 3 <NA>  y     n     TRUE   
#> 4 <NA>  n     n     NA     
#> 5 <NA>  <NA>  <NA>  NA

EDIT: The first solution (so-called "safe") doesn't work with factor variables (and possibly other classes) as discussed here. Seems like things get coerced to numeric, which is why this (very silly) code gives the desired result:

z0 %>% 
  mutate(new = pmap(., 
     ~ any(as.numeric(factor("y", levels = c("n", "y"))) == 
           c(..1, ..2, ..3))))
9
  • behavior of %in% is different of ==, I tried to replace %in% for == but error came out. Apr 18, 2018 at 15:15
  • The only difference I can think of is that any("y" == x) returns NA when x is all NA while y %in% x returns FALSE in that case. Which do you want?
    – ngm
    Apr 18, 2018 at 15:23
  • I NEED == behavior. see for example any("y" == c("n","n",NA)) and any("y" %in% c("n","n",NA)). Apr 18, 2018 at 15:32
  • 1
    OK - always best to include the desired output in the original question.
    – ngm
    Apr 18, 2018 at 17:31
  • the desired output is the same as z0 %>% apply(1, function(x) any("y" == x)). sorry if it wasn't clear. Apr 18, 2018 at 19:42
2

This will work with factors or character columns.

library(tidyverse)
z0 %>% 
  mutate(new_var = rowSums(.[c('A','B','C')] == 'y', na.rm = T) > 0)

Another option (slower I'd guess) is to use rowwise

z0 %>% 
  mutate_at(c('A', 'B', 'C'), as.character) %>% 
  rowwise %>% 
  mutate(newvar = any(c(A, B, C) == 'y', na.rm = T))
6
  • Should have na.rm = TRUE in there too.
    – ngm
    Apr 18, 2018 at 15:15
  • Unless OP wants NA to be returned when the whole row is NA in which case this approach doesn't work at all.
    – ngm
    Apr 18, 2018 at 15:25
  • Agree with ngm. That isn't what I want Apr 18, 2018 at 15:43
  • @NicolasMolano Edited Apr 18, 2018 at 16:07
  • @Renu I must point out that the solution which uses rowSums isn't good. In the second, It works but taking na.rm =F. It should be noted the use of transpose in your solution, this highlights the difficulty of using functions based on rows to create variables with mutate. Apr 18, 2018 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.