如何使用dplyr以新列名作为字符串重命名选定的列 [英] How to rename selected columns using dplyr with new column names as strings
问题描述
我有以下小标题:
library(tidyverse)
df <- structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5), Sepal.Width = c(3.5,
3, 3.2, 3.1, 3.6), Petal.Length = c(1.4, 1.4, 1.3, 1.5, 1.4)), .Names = c("Sepal.Length",
"Sepal.Width", "Petal.Length"), row.names = c(NA, 5L), class = c("tbl_df",
"tbl", "data.frame"))
看起来像这样:
> df
# A tibble: 5 × 3
Sepal.Length Sepal.Width Petal.Length
* <dbl> <dbl> <dbl>
1 5.1 3.5 1.4
2 4.9 3.0 1.4
3 4.7 3.2 1.3
4 4.6 3.1 1.5
5 5.0 3.6 1.4
我要做的是替换 Sepal.Length
和带附加字符串
导致: to_app<- .xxx
的Petal.Length
What I want to do is to replace Sepal.Length
and Petal.Length
with appended string to_app <- ".xxx"
resulting in:
Sepal.Length.xxx Sepal.Width Petal.Length.xxx
5.1 3.5 1.4
4.9 3.0 1.4
4.7 3.2 1.3
4.6 3.1 1.5
5.0 3.6 1.4
我尝试了以下错误:
>df %>% rename(paste(Sepal.Length,to_app,sep="") = Petal.Length,paste(Sepal.Width,to_app,sep="") = Petal.Length)
Error: unexpected '=' in "df %>% rename(paste(Sepal.Length,to_app,sep="") ="
推荐答案
如果要使用dplyr的重命名
函数,最好创建一个命名矢量/列表,并使用标准评估版中的 .dots
参数进行调用:
If you want to use dplyr's rename
function, it would be best to create a named vector / list and call it using the .dots
argument in the standard evaluation version:
cols <- c("Sepal.Length", "Petal.Length")
to_app <- ".xxx"
cols <- setNames(cols, paste0(cols, to_app))
df %>% rename_(.dots = cols)
## A tibble: 5 × 3
# Sepal.Length.xxx Sepal.Width Petal.Length.xxx
#* <dbl> <dbl> <dbl>
#1 5.1 3.5 1.4
#2 4.9 3.0 1.4
#3 4.7 3.2 1.3
#4 4.6 3.1 1.5
#5 5.0 3.6 1.4
但是请注意,此方法可能会随着dplyr的下一个版本0.6.0更改(请参见例如 http://blog.rstudio.org/2017/04/ 13 / dplyr-0-6-0-coming-soon / 和 http:// dplyr.tidyverse.org/articles/programming.html )。
Note however, that this approach is subject to change with the next version 0.6.0 of dplyr (see e.g. http://blog.rstudio.org/2017/04/13/dplyr-0-6-0-coming-soon/ and http://dplyr.tidyverse.org/articles/programming.html).
这篇关于如何使用dplyr以新列名作为字符串重命名选定的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!