R 将作为文件名的列名作为年份添加到数据框中
我是R新手。我在本地pc的一个目录中有多个文件。我已将它们导入R并添加了列名,如下所示。现在,我需要将年份添加到与文件名对应的每个数据帧中。例如,第一个文件名为1950,第二个文件名为1951,依此类推。如何将年份作为列名称添加到R中的这些值R 将作为文件名的列名作为年份添加到数据框中,r,R,我是R新手。我在本地pc的一个目录中有多个文件。我已将它们导入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 30
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 )
}
ldf您可以通过直接从文件名获取年份来添加包含年份的列。我还使用了lappy
而不是循环遍历每个文件
在下面的代码中,该函数读取单个文件,并添加一列,其中包含该文件的年份。由于文件名中包含年份,因此只需使用substr
从文件名中获取年份即可lappy
将该函数应用于listtxt
中的每个文件名,从而生成一个列表,其中每个元素都是一个数据帧。然后您只需将所有列表元素绑定到单个数据帧中
ldf = lapply(listtxt, function(x) {
dat = read.table(x, header=FALSE, sep=",")
# Add column names
names(dat) = c('Name', 'Sex', 'Number')
# Add a column with the year
dat$Year = substr(x,1,4)
return(dat)
})
# Combine all the individual data frames into a single data frame
df = do.call("rbind", ldf)
除了do.call(“rbind”,ldf)
之外,您还可以使用dplyr
包中的rbind\u all
,如下所示:
library(dplyr)
df = rbind_all(ldf)
我无法在上面的@eipi10答案中添加评论,所以我只能在这里添加。我刚刚尝试了这个,它工作得很好(谢谢-我会搜索几个小时,但没有运气),但得到的信息是,rbind_all是不推荐的。dplyr解决方案现在是:
library(dplyr)
df = bind_rows(ldf)
@帕斯卡:答案被接受了,我在周六点击了复选标记。我希望这没问题。