DeltaIV DeltaIV - 4 months ago 9
R Question

Modify a variable in a data frame, only for some levels of a factor (possibly with dplyr)

Sample df:

df <- data.frame(x = c(runif(10,0,2*pi),runif(10,0,360)), group = gl(n = 2, k = 10, labels =c("A","B")))


I want to modify
x
only for group
A
(convert it to degrees). With
base
I just do:

df <- within(df,x[group == "A"] <- x[group == "A"]*180/pi)


I was wondering if there could be a way to do this with
dplyr
. This is wrong:

df <- df %>% filter(group == "A") %>% mutate(x = x*180/pi)


Because it returns only the subset of
df
where
group == "A"
. Is there a (simple) way to do this, or is this a case where
base
trumps
dplyr
for ease of use?

Answer

We can use ifelse to create the logical condition, and based on that we either do the arithmetic calculation or else return the original values.

df %>%
    mutate(x = ifelse(group=="A", x*180/pi, x))

Or as @AlexIoannides mentioned, if_else from dplyr can be used so as the type should be taken care of.


In data.table, this can be done by assignment in place and should be more efficient.

library(data.table)
setDT(df)[group=="A", x := x*180/pi]