如何从R的数据框中选择和重命名一长列? [英] How can I select and rename a long list of columns from a data frame in R?
问题描述
我有一个包含许多列的数据集,我必须选择其中的一部分并将其重命名以偶尔进行分析。目前,我使用软件包 dplyr
中的 select
。但是,每次为许多属性进行设置都非常复杂。有更好的方法吗?
I have a data set with many columns, I have to select a part of them and rename them to analyse occasionally. At moment I use select
from package dplyr
. But it was to complicated to do the setting every time for many attributes. Are there are better methods to do that?
例如,我使用数据集 mtcars
> head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
我要选择以下列: mpg
, cyl
,并将其重命名为 x
, y
I want to select the columns: mpg
, cyl
, and rename them as x
,y
此刻我使用:
> df <- mtcars %>% select(x=mpg, y=cyl)
> head(df)
x y
Mazda RX4 21.0 6
Mazda RX4 Wag 21.0 6
Datsun 710 22.8 4
Hornet 4 Drive 21.4 6
Hornet Sportabout 18.7 8
Valiant 18.1 6
它可以工作,但是当我经常更改参数时会很麻烦括号。我希望使用列表来解决此问题,但这不起作用。
It works, but it is cumbersome when I often change the parameters in the parenthesis. I wish to use a list to solve the problem, but it doesn't work.
例如,我希望创建一个属性列表以使其变得容易:
For example I wish to create a attributes list to make it easy:
myselection <- c(
x = mpg,
y = cyl
)
df <- mtcars %>% select(myselection) # It is wrong!
但这是错误的,如何使它起作用?
But it is wrong, how can I make it work?
推荐答案
您要使用非标准评估(从技术上讲,这是标准评估,而dplyr的常规用法是NSE),请参见 vignette( nse )
:
You want non standard evalation (well technically, this is standard evaluation, and normal dplyr use is NSE), see vignette("nse")
:
library(dplyr)
dots <- list(x="mpg", y="cyl")
select_(mtcars, .dots = dots)
这篇关于如何从R的数据框中选择和重命名一长列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!