有没有一种方法可以将列表定义为循环中的观察?例如,只要data.frame的另一个观察满足特定条件,我就可以运行下面的代码将每个列表替换为观察,就像下面的代码一样,但在运行循环之前,我需要将lists
创建为NULL
lists
的集合。此外,我还没有弄清楚如何将list
放置在创建data.frame
的行中——有办法做到这一点吗?
这是代码:
#line that creates the data.frame: I wished to know how to place the list
#(at the line after creating the data.frame object) inside the data.frame function.
df = data.frame(x=1:10)
#line that creates the list as NULL values before replacing them in the loop
df$y = list(c())
#random replacement condition
df$z = c(0,0,1,0,1,0,1,0,0,0)
#Loop: could I create the list variable on the run without creating it before the loop?
for(i in 1:10) {
if (df$z[i]==1) {
df$y[i] = list(c("a","b"))
}
}
如果有一种更先进的技术或建议的方法来遵循一些原则(例如整洁(,如果有人能参考它,我会很高兴。
我不确定您为什么要这样做,但您可以将代码简化为
df <- data.frame(x = 1:10, z = c(0,0,1,0,1,0,1,0,0,0))
df$y <- ifelse(df$z == 1, list(c("a","b")), list())
并且它将给出相同的结果。