1
我有一個數據框,包含組列和幾個數字列。另外,我有一個變量,它存儲了我需要排名觀察的列名。之所以這樣說,是我的數據幀基於動態變量名稱的組的排名觀察
> 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,但不能使之成爲我的方案工作。
你的方法用'as.name() ''''''''''''''''''''''''''''''如果你從'rlang'周圍包裹unquote運算符'UQ()',將會起作用 –