Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply condition to whole row with dplyr

Tags:

r

dplyr

For example, in a data.table I have three columns. I want to change each row based on the condition of a single column. In this example, if column a == 4, all columns of that row are multiplied by 4.

Written with all variables this would look like this:

a <- c(1,2,3,4,5)
b <- c(2,4,6,7,8)
c <- c(3,6,9,0,3)

data.frame(a,b,c) %>% rowwise() %>% mutate(a=ifelse(a==4,a*4,a),
                                           b=ifelse(a==4,b*4,b),
                                           c=ifelse(a==4,c*4,c))

Is there a way to simply put the condition in one line without writing each column? I would imagine something like this:

data.frame(a,b,c) %>% rowwise() %>% mutate(.=ifelse(a==4,.*4,.))
like image 585
Sebastian Avatar asked Jan 21 '26 13:01

Sebastian


1 Answers

This is what mutate_each was designed for, but for some reason all dplyr solutions are not giving the right answer for cell [4, 'b'].

a <- c(1,2,3,4,5)
b <- c(2,4,6,7,8)
c <- c(3,6,9,0,3)

A <- data.frame(a,b,c) %>% rowwise() %>% mutate(a=ifelse(a==4,a*4,a),
                                                b=ifelse(a==4,b*4,b),
                                                c=ifelse(a==4,c*4,c))
B <- data.frame(a,b,c) %>% mutate(a=ifelse(a==4,a*4,a),
                                  b=ifelse(a==4,b*4,b),
                                  c=ifelse(a==4,c*4,c))

C <- data.frame(a,b,c) %>% 
  mutate_each(funs(ifelse(a == 4, . * 4, .)))

D <- data.frame(a,b,c) %>%
  rowwise() %>%
  mutate_each(funs(ifelse(a == 4, . * 4, .)))

E <- data.frame(a,b,c)
E[E$a == 4, ] <- E[E$a == 4, ] * 4

all.equal(A, B)
#TRUE
all.equal(A, C)
#TRUE
all.equal(A, D)
#TRUE
all.equal(A, E)
#FALSE

The base code from zx8754 is the only one with the correct answer, in the others only a gets multiplied by 4. I don't quite understand why.

It may be a bug (?). You might want to file an issue on Github.

like image 55
Axeman Avatar answered Jan 24 '26 11:01

Axeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!