简体   繁体   中英

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:

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)     
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM