相关疑难解决方法(0)

dplyr可以汇总几个变量而不列出每个变量吗?

dplyr非常快,但我想知道我是否遗漏了一些东西:是否有可能总结出几个变量.例如:

library(dplyr)
library(reshape2)

(df=dput(structure(list(sex = structure(c(1L, 1L, 2L, 2L), .Label = c("boy", 
"girl"), class = "factor"), age = c(52L, 58L, 40L, 62L), bmi = c(25L, 
23L, 30L, 26L), chol = c(187L, 220L, 190L, 204L)), .Names = c("sex", 
"age", "bmi", "chol"), row.names = c(NA, -4L), class = "data.frame")))

   sex age bmi chol
1  boy  52  25  187
2  boy  58  23  220
3 girl  40  30  190
4 girl  62  26  204

dg=group_by(df,sex)
Run Code Online (Sandbox Code Playgroud)

使用这个小型数据帧,它很容易编写

summarise(dg,mean(age),mean(bmi),mean(chol))
Run Code Online (Sandbox Code Playgroud)

而且我知道,为了得到我想要的东西,我可以融化,获得手段,然后如dcast

dm=melt(df, id.var='sex')
dmg=group_by(dm, sex, variable); …
Run Code Online (Sandbox Code Playgroud)

r dplyr

73
推荐指数
2
解决办法
4万
查看次数

dplyr:如何在函数中使用group_by?

我想dplyr::group_by在另一个函数中使用函数,但我不知道如何将参数传递给这个函数.

有人能提供一个有效的例子吗?

library(dplyr)
data(iris)
iris %.% group_by(Species) %.% summarise(n = n()) # 
## Source: local data frame [3 x 2]
##      Species  n
## 1  virginica 50
## 2 versicolor 50
## 3     setosa 50

mytable0 <- function(x, ...) x %.% group_by(...) %.% summarise(n = n())
mytable0(iris, "Species") # OK
## Source: local data frame [3 x 2]
##      Species  n
## 1  virginica 50
## 2 versicolor 50
## 3     setosa 50

mytable1 <- function(x, key) x …
Run Code Online (Sandbox Code Playgroud)

r dplyr nse tidyeval

43
推荐指数
3
解决办法
2万
查看次数

标签 统计

dplyr ×2

r ×2

nse ×1

tidyeval ×1