Dear all, I want to assign a list to one column of data.frame where the name of the column is a variable. I tried the following:
Using R version 3.3.2 > df <- iris[1:3, ] > df # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa > mylist <- list(c(1,2,3),c(1),c()) > mylist # [[1]] # [1] 1 2 3 # # [[2]] # [1] 1 # # [[3]] # NULL > n1 <- 'new1' > df$n1 <- mylist > n2 <- 'new2' > df[,n2] <- mylist # Warning message: # In `[<-.data.frame`(`*tmp*`, , "new4", value = list(c(1, 2, 3), : # provided 3 variables to replace 1 variables > n3 <- 'new3' > df[,n3] <- I(mylist) # Warning message: # In `[<-.data.frame`(`*tmp*`, , "new3", value = list(c(1, 2, 3), : # provided 3 variables to replace 1 variables > eval(parse(text = paste0("df$","new4","<- mylist"))) > df # Sepal.Length Sepal.Width Petal.Length Petal.Width Species n1 new2 new3 new4 # 1 5.1 3.5 1.4 0.2 setosa 1, 2, 3 1 1 1, 2, 3 # 2 4.9 3.0 1.4 0.2 setosa 1 2 2 1 # 3 4.7 3.2 1.3 0.2 setosa NULL 3 3 NULL The "eval" works correctly, however, if I want to avoid using "eval", what should I do? Thanks! ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.