SavedByJESUS
SavedByJESUS

Reputation: 3334

Naming the columns of data frames in a list

I am trying to use the lapply function to name data frames in a list.

I have a list, l, of 2 data frame, which contain two columns each. I would like to name the columns of the two data frames the same way: for the first column, "a" and for the second column "b". I thought the lapply function would help me do that; however, it did not work out as expected (maybe I am using it the wrong way). It seems that lapply will always produce some output and cannot be used for assignment (at least not the way I use it).

l <- list(df1 = as.data.frame(replicate(2, rnorm(5))),
          df2 = as.data.frame(replicate(2, runif(5))))

lapply(l, function(x) colnames(x) <- letters[1:2])

$df1
[1] "a" "b"

$df2
[1] "a" "b"

Upvotes: 2

Views: 145

Answers (1)

alko989
alko989

Reputation: 7938

You were almost there:

l <- list(df1 = as.data.frame(replicate(2, rnorm(5))),
          df2 = as.data.frame(replicate(2, runif(5))))

lapply(l, function(x) {
    colnames(x) <- letters[1:2]
    x
})

You have to return the data.frame x


Form @thelatemail's comment, a really elegant solution:

lapply(l, setNames, letters[1:2])

Using setnames from the data.table package (thanks to Ananda Mahto)

library(data.table)
lapply(l, setnames, letters[1:2])

Using this approach the data.frames are not copied. Useful for BIG data.frames.

Upvotes: 4

Related Questions