如何在不合并 r 中的数据帧的情况下从多个数据帧的列名中删除“-”和 space
How to Remove "-" and space from column names of multiple data frames without merging the data frames in r
我有 30 个数据框说:data_01、data_02、....、data_30。我正在尝试从列名中删除 space 和“-”,并使用以下代码将它们变成小写:
names(data_02) %<>%
stringr::str_remove_all("-") %>%
str_replace_all( "\s", "_" ) %>% tolower
我必须为 30 个数据帧重复此过程 30 次。
有什么方法可以在不合并数据帧的情况下使用一个代码对所有数据帧执行此过程。
我试过这个:
制作数据框列表
dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))
lapply(dfs, function() {names () %<>%
stringr::str_remove_all("-") %>%
str_replace_all( "\s", "_" ) %>% tolower}, return())
但它不起作用。
ps: 我是新用户,了解不多。我将衷心感谢您的帮助。
感谢您的帮助。
lapply
中的匿名函数需要带参数(return()
需要在函数内部)。没有可重现的例子无法测试,但我猜这会起作用:
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)
})
我有 30 个数据框说:data_01、data_02、....、data_30。我正在尝试从列名中删除 space 和“-”,并使用以下代码将它们变成小写:
names(data_02) %<>%
stringr::str_remove_all("-") %>%
str_replace_all( "\s", "_" ) %>% tolower
我必须为 30 个数据帧重复此过程 30 次。
有什么方法可以在不合并数据帧的情况下使用一个代码对所有数据帧执行此过程。
我试过这个: 制作数据框列表
dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))
lapply(dfs, function() {names () %<>%
stringr::str_remove_all("-") %>%
str_replace_all( "\s", "_" ) %>% tolower}, return())
但它不起作用。
ps: 我是新用户,了解不多。我将衷心感谢您的帮助。 感谢您的帮助。
lapply
中的匿名函数需要带参数(return()
需要在函数内部)。没有可重现的例子无法测试,但我猜这会起作用:
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)
})