Ответ 1
Я думаю, что вы смотрите документацию для plyr::rename
, а не dplyr::rename
. Вы сделали бы что-то подобное с помощью dplyr::rename
:
iris %>% rename_(.dots=setNames(names(.), tolower(gsub("\\.", "_", names(.)))))
(Совсем связанный вопрос: Введите имена новых столбцов в качестве строки в функции переименования dplyr)
В середине цепочки dplyr
(%>%
) я хотел бы заменить несколько имен столбцов на функции их старых имен (используя tolower
или gsub
и т.д.)
library(tidyr); library(dplyr)
data(iris)
# This is what I want to do, but I'd like to use dplyr syntax
names(iris) <- tolower( gsub("\\.", "_", names(iris) ) )
glimpse(iris, 60)
# Observations: 150
# Variables:
# $ sepal_length (dbl) 5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6,...
# $ sepal_width (dbl) 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4,...
# $ petal_length (dbl) 1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4,...
# $ petal_width (dbl) 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3,...
# $ species (fctr) setosa, setosa, setosa, setosa, s...
# the rest of the chain:
iris %>% gather(measurement, value, -species) %>%
group_by(species,measurement) %>%
summarise(avg_value = mean(value))
Я вижу ?rename
принимает аргумент replace
как named character vector, with new names as values, and old names as names.
Итак, я попробовал:
iris %>% rename(replace=c(names(iris)=tolower( gsub("\\.", "_", names(iris) ) ) ))
но этот (a) возвращает Error: unexpected '=' in iris %>% ...
и (b) требует ссылки по имени фрейма данных из предыдущей операции в цепочке, что в моем реальном случае использования я не мог сделать.
iris %>%
rename(replace=c( )) %>% # ideally the fix would go here
gather(measurement, value, -species) %>%
group_by(species,measurement) %>%
summarise(avg_value = mean(value)) # I realize I could mutate down here
# instead, once the column names turn into values,
# but that not the point
# ---- Desired output looks like: -------
# Source: local data frame [12 x 3]
# Groups: species
#
# species measurement avg_value
# 1 setosa sepal_length 5.006
# 2 setosa sepal_width 3.428
# 3 setosa petal_length 1.462
# 4 setosa petal_width 0.246
# 5 versicolor sepal_length 5.936
# 6 versicolor sepal_width 2.770
# ... etc ....
Я думаю, что вы смотрите документацию для plyr::rename
, а не dplyr::rename
. Вы сделали бы что-то подобное с помощью dplyr::rename
:
iris %>% rename_(.dots=setNames(names(.), tolower(gsub("\\.", "_", names(.)))))
Это очень поздний ответ, май 2017 года
По состоянию на dplyr 0.5.0.9004
, скоро будет 0.6.0, в пакет добавлено много новых способов переименования столбцов, соответствующих оператору труб maggritr
%>%
.
Эти функции:
Существует много разных способов использования этих функций, но проблема, связанная с вашей проблемой, с использованием пакета stringr
заключается в следующем:
df <- df %>%
rename_all(
funs(
stringr::str_to_lower(.) %>%
stringr::str_replace_all(., '\\.', '_')
)
)
Итак, продолжайте с сантехникой:) (каламбур не предназначен).
Вот путь вокруг несколько неудобного синтаксиса rename
:
myris <- iris %>% setNames(tolower(gsub("\\.","_",names(.))))
Для этого конкретного [но довольно распространенного] случая функция уже написана в пакете janitor:
library(janitor)
iris %>% clean_names()
## sepal_length sepal_width petal_length petal_width species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
## . ... ... ... ... ...
так что все вместе,
iris %>%
clean_names() %>%
gather(measurement, value, -species) %>%
group_by(species,measurement) %>%
summarise(avg_value = mean(value))
## Source: local data frame [12 x 3]
## Groups: species [?]
##
## species measurement avg_value
## <fctr> <chr> <dbl>
## 1 setosa petal_length 1.462
## 2 setosa petal_width 0.246
## 3 setosa sepal_length 5.006
## 4 setosa sepal_width 3.428
## 5 versicolor petal_length 4.260
## 6 versicolor petal_width 1.326
## 7 versicolor sepal_length 5.936
## 8 versicolor sepal_width 2.770
## 9 virginica petal_length 5.552
## 10 virginica petal_width 2.026
## 11 virginica sepal_length 6.588
## 12 virginica sepal_width 2.974
Моя красноречивая попытка использовать base, stringr и dplyr:
EDIT: library (tidyverse) теперь включает в себя все три библиотеки.
library(tidyverse)
library(maggritr) # Though in tidyverse to use %>% pipe you need to call it
# library(dplyr)
# library(stringr)
# library(maggritr)
names(iris) %<>% # pipes so that changes are apply the changes back
tolower() %>%
str_replace_all(".", "_")
Я делаю это для построения функций с трубопроводом.
my_read_fun <- function(x) {
df <- read.csv(x) %>%
names(df) %<>%
tolower() %>%
str_replace_all("_", ".")
tempdf %<>%
select(a, b, c, g)
}
Оба select_all()
select()
и select_all()
могут использоваться для переименования столбцов.
Если вы хотите переименовать только определенные столбцы, вы можете использовать select
:
iris %>%
select(sepal_length = Sepal.Length, sepal_width = Sepal.Width, everything()) %>%
head(2)
sepal_length sepal_width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
rename
делает то же самое, просто без необходимости включать everything()
:
iris %>%
rename(sepal_length = Sepal.Length, sepal_width = Sepal.Width) %>%
head(2)
sepal_length sepal_width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
select_all()
работает со всеми столбцами и может принимать функцию в качестве аргумента:
iris %>%
select_all(tolower)
iris %>%
select_all(~gsub("\\.", "_", .))
или объединение двух:
iris %>%
select_all(~gsub("\\.", "_", tolower(.))) %>%
head(2)
sepal_length sepal_width petal_length petal_width species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa