在Indometh
数据框中,我想通过time
得到Subject
的总和,但还要保留所有其他列。
到目前为止,我的代码:
group_by(.data = Indometh, Subject) %>% summarise(TimeSum=sum(time))
这给了我一个只有Subject
和TimeSum
列的数据框。如何在不知道它们名称的情况下在此数据框中包含所有其他列(或其他任何列)?
答案 0 :(得分:1)
使用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)
答案 1 :(得分:1)
您可以使用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