[英]Loop over list in R gives error
I am creating many new variables, always the same based on existing variables. 我正在创建许多新变量,基于现有变量总是相同。 Given that it is always the same, I would like to do it in a loop.
鉴于总是一样,我想循环执行。
varlist <- list("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10")
for (i in varlist){
mydata$Var2_[i] <- (mydata$Var1_[i]/2)
}
How do I refer to "i"? 我怎么称呼“我”? I tried ,i,;[i], [[i]] and just i, but always get errors:
我尝试了[i]; [i],[[i]]和我,但是总是会出错:
1: In `[<-.data.table`(x, j = name, value = value) :
Adding new column 'PP_onesided_' then assigning NULL (deleting it).
It looks like you are trying to concatenate a column name together. 看起来您正在尝试将列名称连接在一起。 Try doing it like this...
尝试这样做...
varlist <- c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10")
for (i in varlist){
mydata[, paste0("Var2_", i)] <- (mydata[, paste0("Var1_", i)] / 2)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.