Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine mutate_all and ifelse

Tags:

r

dplyr

I would like to iterate over all columns of a data.frame with mutate_all() and then selectively change values using ifelse().

testdf <- data.frame("a"=c(1,2,3), "b"=c(4,5,6), "c"=c(7,8,9))

mutate_all(testdf, ifelse(.>9,10,.))

But this does not work. I always get "object '.' not found". How do I refer to the individual values passed through the mutate_all() function? I thought the '.' worked that way? This works:

mutate_all(testdf, funs(.*2))
like image 502
Claudius Avatar asked Dec 12 '18 03:12

Claudius


1 Answers

Try any of these:

testdf %>% mutate_all(function(x) ifelse(x>9,10,x))

testdf %>% mutate_all(funs(ifelse(.>9,10,.)))

testdf %>% mutate_all(testdf, ~ifelse(.>9,10,.))

testdf %>% mutate_all(~ pmin(., 10))

testdf %>% mutate_all(pmin, 10)

testdf %>% mutate_all(~ replace(., . > 9, 10))

testdf %>% replace(. > 9, 10) 

Last two are per Ronak Shah comment below.

Update

Since this question was asked dplyr 1.0.0 has come out and introduced a new across function which is used with mutate and is now preferred over the mutate_* functions.

testdf %>% mutate(across(, ~ pmin(., 10)))
like image 116
G. Grothendieck Avatar answered Sep 28 '22 18:09

G. Grothendieck