Yamuna_dhungana
Yamuna_dhungana

Reputation: 663

How do I change the case of all dataframes in list in R

Say I have a list with multiple dataframes. I would like to change the column names to lower case in all dataframes. How do I do it.

Say if my list is lst1, I tried lapply(lst1, function(x){colnames(x) <- tolower(colnames(x))}).

Upvotes: 0

Views: 238

Answers (2)

akrun
akrun

Reputation: 886938

We need to return the dataset or else it returns only the column names which is the last assigned output

lst2 <- lapply(lst1, function(x){
       colnames(x) <- tolower(colnames(x))
         x})

Or another option is to use setNames

lst2 <- lapply(lst1, function(x) setNames(x, tolower(names(x))))

Or using tidyverse

library(dplyr)
library(purrr)
map(lst1, ~ .x %>%
              rename_all(~ tolower(.)))

NOTE: It is always good to specify colnames instead of names as names can be different for a matrix. But colnames work for both

NOTE2: return is not really needed in R

Upvotes: 2

Duck
Duck

Reputation: 39585

It can also be used names() and return(). Here an example:

#Data
list1 <- list(iris,mtcars)
list1 <- lapply(list1, function(x) {names(x)<-toupper(names(x));return(x)})
lapply(list1,names)

So our input names look like:

[[1]]
[1] "SEPAL.LENGTH" "SEPAL.WIDTH"  "PETAL.LENGTH" "PETAL.WIDTH"  "SPECIES"     

[[2]]
 [1] "MPG"  "CYL"  "DISP" "HP"   "DRAT" "WT"   "QSEC" "VS"   "AM"   "GEAR" "CARB"

Now the code:

#Code
list2 <- lapply(list1, function(x){names(x) <- tolower(names(x));return(x)})
lapply(list2,names)

How the names will look now:

[[1]]
[1] "sepal.length" "sepal.width"  "petal.length" "petal.width"  "species"     

[[2]]
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"

Upvotes: 0

Related Questions