I\'m pretty frustrated because I dont know how I achieve the naming of the columns and rows in a list of data.frames. I mean I want to avoid using a loop. So I figured I cou
I'll prefer setNames
in this case
set.seed(1)
datalist <- list(dat1 = data.frame(A = 1:10, B = rnorm(10)),
dat2 = data.frame(C = 100:109, D = rnorm(10))
)
lapply(datalist, names)
## $dat1
## [1] "A" "B"
## $dat2
## [1] "C" "D"
datalist <- lapply(datalist, setNames, paste0("col", 1:2))
lapply(datalist, names)
## $dat1
## [1] "col1" "col2"
## $dat2
## [1] "col1" "col2"
EDIT
A more general solution to modify rownames and colnames within a list
lapply(datalist, "colnames<-", paste0("col", 1:2))
lapply(datalist, "rownames<-", letters[1:10])
You need to remember that the object x
inside the lapply
is not the original object, but a copy. Changing the colnames
of the copy does not impact the original object. You need to return x
in order to get a new copy of the object that includes the new names.
new_obj = lapply(a, function(x) {
colnames(x) <- paste("col",1:10,sep="")
return(x)
})