向表或数据框列表中的每个元素添加一个新列 [英] Adding a new column to each element in a list of tables or data frames
问题描述
我有一个文件列表.我还有一个名称"列表,我从这些文件的实际文件名中substr()
.我想为列表中的每个文件添加一个新列.此列将包含名称"中相应元素的重复次数乘以文件中的行数.
I have a list of files. I also have a list of "names" which I substr()
from the actual filenames of these files. I would like to add a new column to each of the files in the list. This column will contain the corresponding element in "names" repeated times the number of rows in the file.
例如:
df1 <- data.frame(x = 1:3, y=letters[1:3])
df2 <- data.frame(x = 4:6, y=letters[4:6])
filelist <- list(df1,df2)
ID <- c("1A","IB")
伪代码
for( i in length(filelist)){
filelist[i]$SampleID <- rep(ID[i],nrow(filelist[i])
}
//基本上在文件列表中的每个数据帧中创建一个新列,并用重复的相应 ID 值填充该列
// basically create a new column in each of the dataframes in filelist, and fill the column with repeted corresponding values of ID
我的输出应该是这样的:
my output should be like:
filelist[1]
应该是:
x y SAmpleID
1 1 a 1A
2 2 b 1A
3 3 c 1A
fileList[2]
x y SampleID
1 4 d IB
2 5 e IB
3 6 f IB
等等......
任何想法如何做到.
推荐答案
另一种解决方案是使用 cbind,并利用 R 将回收较短向量的值这一事实.
An alternate solution is to use cbind, and taking advantage of the fact that R will recylce values of a shorter vector.
例如
x <- df2 # from above
cbind(x, NewColumn="Singleton")
# x y NewColumn
# 1 4 d Singleton
# 2 5 e Singleton
# 3 6 f Singleton
不需要使用rep
.R 为您做到了这一点.
There is no need for the use of rep
. R does that for you.
因此,您可以将 cbind(filelist[[i]], ID[[i]])
放在您的 for 循环
中,或者如@Sven 指出的那样,您可以使用更干净的mapply
:
Therfore, you could put cbind(filelist[[i]], ID[[i]])
in your for loop
or as @Sven pointed out, you can use the cleaner mapply
:
filelist <- mapply(cbind, filelist, "SampleID"=ID, SIMPLIFY=F)
这篇关于向表或数据框列表中的每个元素添加一个新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!