[英]How to use "summarise" from dplyr with dynamic column names?
我正在使用 R 中 dplyr 包中的summarize
函數summarize
表中的組均值。我想使用存儲在另一個變量中的列名字符串動態執行此操作。
以下是“正常”方式,當然可以工作:
myTibble <- group_by( iris, Species)
summarise( myTibble, avg = mean( Sepal.Length))
# A tibble: 3 x 2
Species avg
<fct> <dbl>
1 setosa 5.01
2 versicolor 5.94
3 virginica 6.59
但是,我想做這樣的事情:
myTibble <- group_by( iris, Species)
colOfInterest <- "Sepal.Length"
summarise( myTibble, avg = mean( colOfInterest))
我已經閱讀了dplyr頁面的編程,並且我嘗試了一堆quo
、 enquo
、 !!
的組合!!
, .dots=(...)
等,但我還沒有想出正確的方法來做到這一點。
我也知道這個答案,但是,1) 當我使用標准評估函數standardise_
,R 告訴我它已經貶值,並且 2) 這個答案看起來一點也不優雅。 那么,有沒有一種好的,簡單的方法來做到這一點?
謝謝!
1)使用!!sym(...)
像這樣:
colOfInterest <- "Sepal.Length"
iris %>%
group_by(Species) %>%
summarize(avg = mean(!!sym(colOfInterest))) %>%
ungroup
給予:
# A tibble: 3 x 2
Species avg
<fct> <dbl>
1 setosa 5.01
2 versicolor 5.94
3 virginica 6.59
2)第二種方法是:
colOfInterest <- "Sepal.Length"
iris %>%
group_by(Species) %>%
summarize(avg = mean(.data[[colOfInterest]])) %>%
ungroup
當然,這在基礎 R 中是直接的:
aggregate(list(avg = iris[[colOfInterest]]), iris["Species"], mean)
另一種解決方案:
iris %>%
group_by(Species) %>%
summarise_at(vars("Sepal.Length"), mean) %>%
ungroup()
# A tibble: 3 x 2
Species Sepal.Length
<fct> <dbl>
1 setosa 5.01
2 versicolor 5.94
3 virginica 6.59
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.