[英]Rename the same column for all excel files in a folder in R
I have multiple excel files in a folder, so I want to clean each file in the folder, then append all the excel files together.我在一个文件夹中有多个 excel 文件,所以我想清理文件夹中的每个文件,然后将所有 excel 文件附加在一起。 I want to rename the first column of all excel files so I am using the following codes :
我想重命名所有 excel 文件的第一列,所以我使用以下代码:
filelist<- list.files(pattern="*.xlsx")
DF <- lapply(filelist,function(i) {
Fu <- read_excel(i, sheet="XX")
colnames(Fu[[i]])[1] <- "Column 1"})
However, I got an error message: Error in colnames<-
( *tmp*
, value = "SCENARIO_KEY") : attempt to set 'colnames' on an object with less than two dimensions.但是,我收到一条错误消息:
colnames<-
( *tmp*
, value = "SCENARIO_KEY") 中的错误:尝试在小于二维的对象上设置“colnames”。 How to fix it?如何解决? Thank you.
谢谢你。
In the lapply
, itself, we can rename.在
lapply
本身,我们可以重命名。 The i
in the loop are each of the element of 'filelist'.循环中的
i
是“filelist”的每个元素。 It cannot be used for subsetting 'Fu'.它不能用于子集 'Fu'。 Instead, we can directly subset the column based on the index as 'Fu' is a single data.frame within each
list
element相反,我们可以根据索引直接对列进行子集,因为“Fu”是每个
list
元素中的单个 data.frame
DF <- lapply(filelist,function(i) {
Fu <- read_excel(i, sheet="XX")
colnames(Fu)[1] <- "Column 1"
Fu
})
Even if the index is right, when we subset a data.frame with [[
to get the column, it returns a vector
and there is dim or column names attribute for a vector即使索引是正确的,当我们使用
[[
对 data.frame 进行子集化以获取列时,它会返回一个vector
并且vector
有 dim 或 column names 属性
mtcars[[1]]
is a vector
是一个
vector
and doing the assignment returns the error because the colnames is NULL
并且执行分配会返回错误,因为 colnames 为
NULL
colnames(mtcars[[1]])
#NULL
colnames(mtcars[[1]]) <- "new column"
Error in
colnames<-
(*tmp*
, value = "new column") : attempt to set 'colnames' on an object with less than two dimensionscolnames<-
(*tmp*
, value = "new column") 中的错误:尝试在小于二维的对象上设置“colnames”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.