我有一个数据框的列表,我试图添加一个矢量的相应元素作为所有观察值的新变量到列表的每个数据帧。添加一个新的列到数据框的列表,但只选择一个矢量的一行
我的问题是:是否有某种“索引”跟踪lapply函数现在在哪一步?我无法找到任何东西,但它会解决我的问题,我相信因为我不需要循环,只能使用timevar <- time[magic.index]
我认为这个例子使我的意思更清晰。
#list of data frames
df1 <- data.frame("Var1" = c(1:10))
df2 <- data.frame("Var1" = c(1:10),"Var2" = c(1:10))
df3 <- data.frame("Var1" = c(1:10),"Var2" = c(1:10),"Var3" = c(1:10))
dfs <- list(df1,df3,df2)
time <- c(1,2,1)
#this is what I want to do with lapply
lapply(dfs, function(x) within(x, timevar <- 1))
dfs2 <- for (i in seq_along(dfs)){
lapply(dfs, function(x) within(x, timevar <- time))
}
#this is what the result should look like
dfs[[1]] <- within(dfs[[1]], timevar <- 1)
dfs[[2]] <- within(dfs[[2]], timevar <- 2)
dfs[[3]] <- within(dfs[[3]], timevar <- 1)
dfs
注意'lapply()'*是*循环。 – gung