![](/img/trans.png)
[英]Applying group_by and summarise on data while keeping all the columns' info
[英]How do I `group_by` and `summarise` while keeping all numeric columns without knowing those columns' names?
在Indometh
數據框中,我想按Subject
獲取time
總和,但還要保留所有其他列。
到目前為止,我的代碼:
group_by(.data = Indometh, Subject) %>% summarise(TimeSum=sum(time))
這給了我一個只有Subject
和TimeSum
列的數據TimeSum
。 如何在此數據框中(或其他任何其他列)包括所有其他列,而不必知道它們的名稱?
使用summarize_if
。 例如,
exd <- data.frame(g = rep(c('a', 'b'), 5),
notthisone = "nope!",
n1 = runif(10),
n2 = runif(10))
summarize_if(group_by(exd, g), is.numeric, mean)
您可以使用mutate()函數添加新列,並保留所有其他內容,如下所示:
library(dplyr) Indometh %>% group_by(Subject) %>% mutate(total = sum(time))
# A tibble: 66 x 4
# Groups: Subject [6]
Subject time conc total
<ord> <dbl> <dbl> <dbl>
1 1 0.25 1.5 31.8
2 1 0.5 0.94 31.8
3 1 0.75 0.78 31.8
4 1 1 0.48 31.8
5 1 1.25 0.37 31.8
6 1 2 0.19 31.8
7 1 3 0.12 31.8
8 1 4 0.11 31.8
9 1 5 0.08 31.8
10 1 6 0.07 31.8
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.