[英]How to rename a specific column of multiple files with a list of names In r?
I have a folder of .txt files. 我有一个.txt文件文件夹。 I have read the files into a list in R by following command:
我已经通过以下命令将文件读入R中的列表中:
filenames <- list.files("/path/to/folder")
datalist = lapply(filenames, function(x)read.table(x, header=T))
Now I want to change the 9th column of each file to the name of file(filename list is the vector of names). 现在,我想将每个文件的第9列更改为文件名(文件名列表是名称的向量)。
do you have any idea how can I do this by using lapply()? 你有什么主意,如何使用lapply()做到这一点? Thanks!
谢谢!
You can change a single column name by position by subsetting colnames
and inserting like in the example below. 您可以通过以下方式按位置更改单个列名称:设置子
colnames
并插入,如以下示例所示。
lst <- list(data.frame('a' = c(1,2,3),
'b' = c(3,5,6)),
data.frame('a' = c(1,2,3),
'b' = c(3,5,6)),
data.frame('a' = c(1,2,3),
'b' = c(3,5,6)))
lapply(lst, function(item) {
colnames(item)[2] <- 'cat' # This would be 9 if you wanted the 9th column
return(item)
})
[[1]]
a cat
1 1 3
2 2 5
3 3 6
[[2]]
a cat
1 1 3
2 2 5
3 3 6
[[3]]
a cat
1 1 3
2 2 5
3 3 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.