Cecmel
Cecmel

Reputation: 21

Mutate based on two arguments

Anyone know how to mutate values in a column with arguments both including the value in the given column and a value of another column. For example, mutate all values in X1 that has NA and that has value 0 in X3. Thinking there should be a way to include both IF and AND.

Something like this. This obviously does not work. Trying to mutate in two columns.

DF <- DF %>% mutate(X1 = ifelse(is.na(X1)) & X3 = 1), 0, X1),
                                  X2 = ifelse(is.na(X2)) & X3 = 1), 0, X2))

Using R.

Upvotes: 2

Views: 136

Answers (1)

Kra.P
Kra.P

Reputation: 15123

You may try(I'm confusing with your condition. If there's a mistake, please let me know.)

DF <- data.frame(
  X1 = c(1,2,NA,4,NA,5),
  X2 = c(NA,2,3,4,1,NA),
  X3 = c(0,1,0,1,1,0)
)

  X1 X2 X3
1  1 NA  0
2  2  2  1
3 NA  3  0
4  4  4  1
5 NA  1  1
6  5 NA  0

DF %>%
  mutate(X1 = ifelse(is.na(X1) & X3 == 0, 0, X1) ,
              X2 = ifelse(is.na(X2)  & X3 == 0, 0, X2))

  X1 X2 X3
1  1  0  0
2  2  2  1
3  0  3  0
4  4  4  1
5 NA  1  1
6  5  0  0

Upvotes: 2

Related Questions