我想用空格替换数据框特征名称中的所有下划线:
library(tidyverse)
names <- c("a_nice_day", "quick_brown_fox", "blah_ha_ha")
example_df <- data.frame(
x = 1:3,
y = LETTERS[1:3],
z = 4:6
)
names(example_df) <- names
尝试:
example_df %>% rename_all(replace = c("_" = " "))
Error: `.funs` must specify a renaming function
也尝试过:
example_df %>% rename_all(funs(replace = c("_" = " ")))
Error: `nm` must be `NULL` or a character vector the same length as `x`
如何用空格替换要素名称中的所有下划线?
答案 0 :(得分:6)
那又怎么样:
example_df %>% select_all(funs(gsub("_", " ", .)))
输出:
a nice day quick brown fox blah ha ha
1 1 A 4
2 2 B 5
3 3 C 6
您也可以使用rename
,但是在这种情况下,您需要以其他方式调用它:
example_df %>% rename_all(function(x) gsub("_", " ", x))
或者简单地:
example_df %>% rename_all(~ gsub("_", " ", .))
答案 1 :(得分:1)
以R为底
colnames(example_df) <- gsub("_", " ", colnames(example_df))