我想使用if else语句更改许多变量。这是我正在使用的代码来完成工作:
df <- df %>%
mutate(p = ifelse(gender == 0, p, ifelse(gender==1, 100 - p,NA)),
t = ifelse(gender == 0, t, ifelse(gender==1, 100 - t,NA)),
c = ifelse(gender == 0, c, ifelse(gender==1, 100 - c,NA)),
s = ifelse(gender == 0, s, ifelse(gender==1, 100 - s,NA)),
i = ifelse(gender == 0, i, ifelse(gender==1, 100 - i,NA)))
但是,是否有使用tidyverse进行这些多项更改的更紧凑的方法?
答案 0 :(得分:1)
您不必每次都必须输入列名称的情况下才将函数分别应用于每个列,而可以使用apply(..)为您执行此操作。
一些数据:
n <- 10
df <- data.frame(matrix(round(rnorm(n*5), 0), ncol= 5))
variablenames <- c("p", "t", "c", "s", "i")
names(df) <- variablenames
df$gender <- sample(0:1, n, replace= TRUE)
您的函数和建议的函数给出相同的结果
df1 <- df %>%
mutate(p = ifelse(gender == 0, p, ifelse(gender==1, 100 - p,NA)),
t = ifelse(gender == 0, t, ifelse(gender==1, 100 - t,NA)),
c = ifelse(gender == 0, c, ifelse(gender==1, 100 - c,NA)),
s = ifelse(gender == 0, s, ifelse(gender==1, 100 - s,NA)),
i = ifelse(gender == 0, i, ifelse(gender==1, 100 - i,NA)))
df2 <- apply(df[ , variablenames], 2, function(x){
ifelse(df$gender == 0, x, ifelse(df$gender==1, 100 - x,NA))
})
df2 <- cbind.data.frame(df2, df$gender)
all(df1 == df2)
TRUE