我是R的新手。我在本地电脑上的一个目录中有多个文件。我已经将它们导入到R中,并添加了列名,如下所示。现在我需要为每个数据框添加与文件名对应的年份。例如,第一个文件名为1950,第二个文件名为1951,以此类推。我该如何在R中添加年份作为列名并赋值?
The output is below
Name Sex Number
1 Linda F 10
2 Mary F 100
3 Patrick M 200
4 Barbara F 300
5 Susan F 500
6 Richard M 900
7 Deborah F 500
8 Sandra F 23
9 Conor M 15
10 Conor F 120
我需要在开头添加另一列,用于表示该文件的年份?
这是生成上述内容的代码。
ldf <- list() # creates a list
listtxt <- dir(pattern = "*.txt") # creates the list of all the txt files in the directory
#Year = 1950
for (k in 1:length(listtxt)) #1:4 4 is the length of the list
{
ldf[[k]] <- read.table(listtxt[k],header=F,sep=",")
colnames(ldf[[k]]) = c('Name', 'Sex', 'Number')
#test = cbind(ldf[[k]], Year )
}
我需要为每个文件增加1年,并将其作为一列值添加?任何帮助都将不胜感激。