在R中,我经常对多个变量执行条件运算。例如:
M_foo <- rnorm(25, 0, 1)
M_foo1 <- rnorm(25, 0, 1)
M_bar <- rnorm(25, 0, 1)
M_bar1 <- rnorm(25, 0, 1)
condition <- c(rep(0, 12), rep(1,13))
d <- as.data.frame(cbind(M_foo, M_bar, M_foo1, M_bar1, condition))
d$M_foo_new <- ifelse(
d$condition == 0, d$M_foo1*2, NA
)
d$M_bar_new <- ifelse(
d$condition == 1, d$M_bar1*2, NA
)
如果我对系统更改名称的多个变量执行此操作,如何将其压缩为更紧凑的工作流程? 现在,我经常将代码复制到MS Word中并搜索并更改变量名称中的相应差异。这可以在R?
中更优雅地完成提前致谢
答案 0 :(得分:0)
如果我们需要重用,那么函数会更好
f1 <- function(dat, col1, val, col2, multiplier) {
i1 <- dat[[col1]]==val
ifelse(i1, dat[[col2]]*multiplier, NA)
}
f1(d, "condition", 0, "M_foo1", 2)
对于多变量创建,请使用lapply
nm1 <- c("M_foo1", "M_bar1")
d[paste0(nm1, "_new")] <- lapply(nm1, function(colN) f1(d, "condition", 0, col2 = colN, 2))
如果乘数/ val不同,则使用Map
d[paste0(nm1, "_new")] <- Map(f1, dat = list(d), "condition", c(0,1), col2 = nm1, 2:3)
答案 1 :(得分:0)
尝试
d[,paste0(names(d[,1:2]),"_new")]=
mapply(function(x,y) {x[d$condition!=y]=NA;x*2}, d[,3:4],unique(d$condition))