1

I have 30 data frames say : data_01, data_02, .... , data_30. I am trying to remove space and "-" from column names and turning them to lower case with this code:

names(data_02) %<>% 
    stringr::str_remove_all("-") %>%
    str_replace_all( "\\s", "_" ) %>% tolower

I have to repeat this process 30 times for 30 data frames.

Is there any way I can do this process for all the data frames with one code without merging the data frames.

I tried this: making list of data frames

dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))
lapply(dfs, function() {names () %<>% 
    stringr::str_remove_all("-") %>%
    str_replace_all( "\\s", "_" ) %>% tolower},  return())

But it's not working.

ps: I am new user and don't know much. I would really appreciate your help. Thanks for your help.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
Ahad Zaman
  • 321
  • 1
  • 9
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Nov 03 '20 at 03:24

1 Answers1

1

Anonymous functions in lapply need to take an argument (and the return() needs to be inside the function). Can't test without a reproducible example, but I would guess this will work:

dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))
lapply(dfs, function(x) {
  names(x) = names(x) %>% 
    stringr::str_remove_all("-") %>%
    str_replace_all( "\\s+", "_" ) %>%  ## added the + just in case
    tolower
  return(x)
})
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294