【发布时间】:2018-08-06 16:52:51
【问题描述】:
我想在dplyr 包中使用filter 或summarise 中的类似功能。所以我有一个数据框(例如mtcars),我需要按因子分组(例如cyl),然后为每个cyl 类型计算一些统计数据和wt 总数的百分比—> wt.pc .
问题是我如何子集/过滤summarise 函数内的wt 列以获得百分比但没有最后10 行?
我试过这段代码,但它返回NA:(
mtcars %>%
group_by(cyl) %>%
summarise(wt = round(sum(wt)),
wt.pc = sum(wt) * 100 / sum(mtcars[, 6]),
wt.pc.short = sum(wt[1:22]) * 100 / sum(mtcars[1:22, 6]),
drat.max = round(max(drat)))
# A tibble: 3 x 5
cyl wt wt.pc wt.pc.short drat.max
<dbl> <dbl> <dbl> <dbl> <dbl>
1 4 25 24.3 NA 5
2 6 22 21.4 NA 4
3 8 56 54.4 NA 4
wt.pc.short — 每个 cyl 的总和百分比(wt),用于较短的数据帧 mtcars[1:22,]
【问题讨论】:
-
head(x,n=-10)给出了向量x中除最后 10 个值之外的所有值,但mtcars中的一组 (cyl==6) 只有 7 个值,所以这不起作用。 (您的1:22缺少dplyr的分组点。)