我有两个相同长度的列表,一个存储一些数据帧,另一个存储字符串.我正在try 弄清楚如何向每个包含字符列表中的相应值的数据帧添加一个新列.例如:
#Staring Dataframes
df1 <- data.frame(v1 = c(1,2,3),
v2 = c("a","b","c"))
df2 <- data.frame(v1 = c(7,8,9),
v2 = c("x","y","z"))
dflist <- list(df1, df2)
#List containing values to add to each dataframe
nameslist <- c('first df value', 'second df value')
#Desired output
df1$v3 <- nameslist[1]
v1 v2 v3
1 a first df value
2 b first df value
3 c first df value
df2$v3 <- nameslist[2]
v1 v2 v3
7 x second df value
8 y second df value
9 z second df value
使用循环似乎很容易做到这一点,但是我如何使用"Apply"函数来实现这一点呢?
我try 了以下几种方法:
output <- lapply(seq_along(dflist), function(i) dflist[[i]]$test = nameslist[[i]])
#This returns a list of character vectors coresponding to nameslist
output <- mapply(function(df, name) df$test = name, dflist, nameslist)
#Returns a single character vector of the values in nameslist
我觉得上面的其中一个肯定相当接近.如果有人能在这方面提供任何指导,我们将不胜感激.蒂娅.