raj*_*jay 6 string r rename dplyr
我试图在我的数据帧中选择一个变量子集,并重命名新数据帧中的变量.我有大量的变量需要重命名.我在用
dplyr::select
dplyr::select_
Run Code Online (Sandbox Code Playgroud)
由于我要重命名的变量数量,我在想是否应该使用字符串变量来重命名,但不确定它是否可能?使用字符串可以帮助我管理newname oldname映射.这是一个例子
dplyr::select
library(dplyr)
library(nycflights13)
set.seed(123)
data <- sample_n(flights, 3)
select(data,yr=year,mon=month,deptime=dep_time)
Run Code Online (Sandbox Code Playgroud)
我怎么能在字符串中传递this的参数,即newvariable = oldvariable参数然后使用
dplyr::select_
col_vector <- c("year", "month", "dep_time")
select_(data, .dots = col_vector)
Run Code Online (Sandbox Code Playgroud)
我想到的字符串是:
rename_vector <- c("yr=year","mon=month","deptime=dep_time")
Run Code Online (Sandbox Code Playgroud)
任何建议都会非常有帮助.
dplyr
用另一种方法dplyr结合setNames来传递新列名的向量:
iris %>%
select(Sepal.Length, Sepal.Width) %>%
setNames(c("sepal_length","sepal_width"))
Run Code Online (Sandbox Code Playgroud)
基础包
setNames(iris[, c("Sepal.Length", "Sepal.Width")],
c("sepal_length", "sepal_width"))
Run Code Online (Sandbox Code Playgroud)
data.table
library(data.table)
setnames(iris, old = c("Sepal.Length", "Sepal.Width"), new = c("sepal_length","sepal_width"))
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以将列表传递给.dotsin dplyr::select_,而不是使用向量,其中名称是新列名称,旧名称是字符.
> 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
.. ... ...
Run Code Online (Sandbox Code Playgroud)