R dplyr ::重命名并选择使用字符串变量 [英] R dplyr:: rename and select using string variable
问题描述
我正在尝试在数据框中选择一个变量子集,并重新命名新数据框中的变量。我有大量的变量,我需要重命名。我正在使用
I am trying to select a subset of variables in my dataframe, and rename the variables in the new dataframe. I have a large number of variables that I would need to rename. I am using
dplyr::select
dplyr::select_
由于我有多个变量要重命名,我在想,如果我应该使用一个字符串变量重命名,但不知道是否可能?使用字符串可以帮助我管理newname旧名映射。这是一个例子
Since I have number of variables to rename, I am thinking if I should use a string variable to rename, but not sure if it could be possible? Using a string helps me to manage the newname oldname mapping. Here is an example
dplyr::select
library(dplyr)
library(nycflights13)
set.seed(123)
data <- sample_n(flights, 3)
select(data,yr=year,mon=month,deptime=dep_time)
问题我可以如何传递一个字符串中的参数,即newvariable = oldvariable参数,然后使用
The question how could I pass the arguments for this in a string, that is the newvariable=oldvariable arguments and then use
dplyr::select_
col_vector <- c("year", "month", "dep_time")
select_(data, .dots = col_vector)
头脑是:
rename_vector <- c("yr=year","mon=month","deptime=dep_time")
任何建议都将非常有帮助。
Any suggestions would be very helpful.
推荐答案
而不是使用向量,您可以在 dplyr :: select_中将列表传递给
,其中名称是新的列名称,旧名称是字符。 .dots
Instead of using a vector, you can pass a list to .dots
in dplyr::select_
, where the names are the new column names and the old names are characters.
> rename_list <- list(sepal_length = "Sepal.Length", sepal_width = "Sepal.Width")
> iris %>% tbl_df %>% select_(.dots = rename_list)
Source: local data frame [150 x 2]
sepal_length sepal_width
(dbl) (dbl)
1 5.1 3.5
2 4.9 3.0
3 4.7 3.2
4 4.6 3.1
5 5.0 3.6
6 5.4 3.9
7 4.6 3.4
8 5.0 3.4
9 4.4 2.9
10 4.9 3.1
.. ... ...
这篇关于R dplyr ::重命名并选择使用字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!