Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter and unfilter in dplyr

Tags:

r

dplyr

What would be the dplyr analog of performing the following operation in base R?

iris$Sepal.Length[iris$Sepal.Length>2] <- iris$Sepal.Length[iris$Sepal.Length>2] * 10

I am trying to use filter but cannot go back to the original data set (without a join)

like image 434
Fernando Hoces De La Guardia Avatar asked Jul 26 '16 20:07

Fernando Hoces De La Guardia


2 Answers

You can use mutate with ifelse to get the same results as comments from @alistaire:

iris %>% mutate(Sepal.Length = ifelse(Sepal.Length > 2, Sepal.Length * 10, Sepal.Length))
like image 93
Psidom Avatar answered Sep 19 '22 21:09

Psidom


If we are using data.table, we can avoid the ifelse and make it faster

library(data.table)
as.data.table(iris)[Sepal.Length > 2, Sepal.Length := Sepal.Length * 10]
like image 27
akrun Avatar answered Sep 22 '22 21:09

akrun