Qianru Song
Qianru Song

Reputation: 331

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. I want to rename the first column of all excel files so I am using the following codes :

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. How to fix it? Thank you.

Upvotes: 2

Views: 262

Answers (1)

akrun
akrun

Reputation: 887108

In the lapply, itself, we can rename. The i in the loop are each of the element of 'filelist'. It cannot be used for subsetting 'Fu'. Instead, we can directly subset the column based on the index as 'Fu' is a single data.frame within each list element

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

mtcars[[1]]

is a vector

and doing the assignment returns the error because the colnames is 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 dimensions

Upvotes: 1

Related Questions