SteveS
SteveS

Reputation: 4040

Change a column value if other specific columns with a specific value?

Consider I have 3 columns:

var1 var2 var3 
1    1    1     
0    1    1     
1    0    1    
0    0    1    
1    1    0    
0    1    0    
1    0    0    
0    0    0 

I want to mutate/change the var3 column if var1 and var2 obey a rule like:

var1 and var2 == 1

I am trying to do this with mutate_at:

df %>% mutate_at(.vars = vars(var1, var2, var3), 
                 .funs = funs(ifelse(var1 & var2, var3 = 5, var3 = 2))

Please advise what I am missing here, it doesn't work.

Upvotes: 0

Views: 55

Answers (3)

Nettle
Nettle

Reputation: 3321

case_when gives a lot of flexibility for rule-making.

 df %>% 
  mutate(
      var3 = case_when(
        var1==1 & var2==1 ~ "my.new.variable",
        TRUE ~ as.character(var3)
      )
    )

#> # A tibble: 8 x 3
#>    var1  var2 var3           
#>   <dbl> <dbl> <chr>          
#> 1  1.00  1.00 my.new.variable
#> 2  0     1.00 1              
#> 3  1.00  0    1              
#> 4  0     0    1              
#> 5  1.00  1.00 my.new.variable
#> 6  0     1.00 0              
#> 7  1.00  0    0              
#> 8  0     0    0
```

Created on 2018-06-03 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0).

Upvotes: 1

Jack Brookes
Jack Brookes

Reputation: 3830

Using ifelse

library(dplyr)


df <- read.table(text = "
var1 var2 var3 
1    1    1     
0    1    1     
1    0    1    
0    0    1    
1    1    0    
0    1    0    
1    0    0    
0    0    0 ", header = TRUE)


df %>% 
  mutate(var3 = ifelse(var1 == 1 & var2 == 1,
                       2,
                       var3))

result:

  var1 var2 var3
1    1    1    2
2    0    1    1
3    1    0    1
4    0    0    1
5    1    1    2
6    0    1    0
7    1    0    0
8    0    0    0

Upvotes: 1

MKR
MKR

Reputation: 20085

You can achieve the same by many different ways, including mutate. You can even do it with dpplyr::mutate_at. You need to change logic slightly as:

library(dplyr)

df %>% mutate_at(vars(c("var3")), funs(ifelse(var1==1 & var2 == 1, 5, 2)))

#   var1 var2 var3
# 1    1    1    5
# 2    0    1    2
# 3    1    0    2
# 4    0    0    2
# 5    1    1    5
# 6    0    1    2
# 7    1    0    2
# 8    0    0    2

Note: The only motivation I can think of about using mutate_at would have been if you had many other columns like var3, var4 etc which were going be processed with similar logic. For just a single column it will just make things more complicated.

Data:

df <- read.table(text =
"var1 var2 var3 
1    1    1     
0    1    1     
1    0    1    
0    0    1    
1    1    0    
0    1    0    
1    0    0    
0    0    0",
header = TRUE, stringsAsFactors = FALSE)

Upvotes: 1

Related Questions