基于动态变量名称

时间:2017-07-26 23:59:48

标签: r

我有一个包含组列和几个数字列的数据框。另外,我有一个变量,用于存储我需要对列表进行排名的列名。说这是我的数据框

> x = "myValue1"
> set.seed(123)
> df = data.frame(myValue1 = rnorm(9, mean = 10),
                  myValue2 = rnorm(9, mean = 2),
                  myGroup = rep(c("a","b","c"), each = 3), 
                  myEntity = paste0("entity",1:9))
> df
   myValue1   myValue2 myGroup myEntity
1  9.439524 1.55433803       a  entity1
2  9.769823 3.22408180       a  entity2
3 11.558708 2.35981383       a  entity3
4 10.070508 2.40077145       b  entity4
5 10.129288 2.11068272       b  entity5
6 11.715065 1.44415887       b  entity6
7 10.460916 3.78691314       c  entity7
8  8.734939 2.49785048       c  entity8
9  9.313147 0.03338284       c  entity9

我想要的是在每个组中使用x中的列返回每个观察的等级(在这种情况下它是myValue1)。所以,我想返回以下数据框

 > library(dplyr)
 > df = data.frame(df %>% 
                   group_by(myGroup) %>% 
                   mutate(myRank = order(myValue1,myEntity)))
 > df
       myValue1   myValue2 myGroup myEntity myRank
    1  9.439524 1.55433803       a  entity1      1
    2  9.769823 3.22408180       a  entity2      2
    3 11.558708 2.35981383       a  entity3      3
    4 10.070508 2.40077145       b  entity4      1
    5 10.129288 2.11068272       b  entity5      2
    6 11.715065 1.44415887       b  entity6      3
    7 10.460916 3.78691314       c  entity7      2
    8  8.734939 2.49785048       c  entity8      3
    9  9.313147 0.03338284       c  entity9      1

这很简单,因为我输入了列名。我的问题是如何使用变量x而不是在此公式中键入列名称。 这是我尝试没有成功(他们都返回错误)

> df = data.frame(df %>% group_by(myGroup) %>% mutate(myRank = order(x,myEntity)))
> df = data.frame(df %>% group_by(myGroup) %>% mutate(myRank = order(as.name(x),myEntity)))
> df = data.frame(df %>% group_by(myGroup) %>% mutate(myRank = order(noquote(x),myEntity)))
> library(plyr)
> df = ddply(df,.(myGroup),transform,Order = rank(as.name(x)))

我也在这里查看了问题similar question,但无法使其适用于我的方案。

1 个答案:

答案 0 :(得分:1)

您可以使用.data代词来引用带字符串的变量:

x <- "myValue1"

df %>% 
  group_by(myGroup) %>% 
  mutate(myRank = order(.data[[x]], myEntity))

或者使用sym()中的rlang与非引号运算符UQ()

df %>% 
  group_by(myGroup) %>% 
  mutate(myRank = order(UQ(rlang::sym(x)), myEntity))