Bruno Guarita
Bruno Guarita

Reputation: 817

Changing from upper to lower case in several data frames

I have several data frames in the environment that I am trying to change the case of the column names in each data frame from upper to lower case. I am using lapply with no success.

df1 <- data.frame(COL1 = 1, COL2 = "test")
df2 <- data.frame(COLL = 10, COLL1 = "test")
df3 <- data.frame(COLLA = 25, COLLA1 = "test")
df4 <- data.frame(COLLAC= "dummy", COLLAC1 = "test")

dfList <- c("df1", "df2", "df3", "df4")

lapply(dfList, function (x){
  names(x) <- tolower(names(x))
})

What I am doing wrong?

Upvotes: 0

Views: 886

Answers (3)

AndS.
AndS.

Reputation: 8110

The other answers work great, but here is another option. Whenever I want to clean-up my column names I always turn to the janitor package. There are lots of options to clean up names with that package. https://cran.r-project.org/web/packages/janitor/janitor.pdf

library(purrr)
library(janitor)

list(df1, df2, df3, df4) %>% 
  map(janitor::clean_names)
#> [[1]]
#>   col1 col2
#> 1    1 test
#> 
#> [[2]]
#>   coll coll1
#> 1   10  test
#> 
#> [[3]]
#>   colla colla1
#> 1    25   test
#> 
#> [[4]]
#>   collac collac1
#> 1  dummy    test

Upvotes: 1

Benjamin
Benjamin

Reputation: 17359

Since you wish to keep all of your data frames in the global environment, this is a situation in which I would prefer using a for loop. This allows you to operate within the global environment (lapply requires that you return something to the global environment).

dfList <- c("df1", "df2", "df3", "df4")
for (i in dfList){
  tmp <- get(i)
  assign(i, setNames(tmp, tolower(names(tmp))))
}

Upvotes: 1

LAP
LAP

Reputation: 6685

Your list does not contain your data.frames. Lists are initiated with list(), not with c(). Here's a working example:

df1 <- data.frame(COL1 = 1, COL2 = "test")
df2 <- data.frame(COLL = 10, COLL1 = "test")
df3 <- data.frame(COLLA = 25, COLLA1 = "test")
df4 <- data.frame(COLLAC= "dummy", COLLAC1 = "test")

dfList <- list(df1, df2, df3, df4)

dfList <- lapply(dfList, function (x){
  names(x) <- tolower(names(x))
  return(x)
})

> dfList
[[1]]
  col1 col2
1    1 test

[[2]]
  coll coll1
1   10  test

[[3]]
  colla colla1
1    25   test

[[4]]
  collac collac1
1  dummy    test

names(dfList) <- paste0("df", 1:4)
list2env(dfList, .GlobalEnv)

Upvotes: 2

Related Questions