我有个小标题:
# A tibble: 10 x 2
term sumsq
<chr> <dbl>
1 a1 10.1
2 a2 5.15
3 a3 45.1
4 a4 7.32
5 a1:a2 0.870
6 a1:a3 14.1
7 a1:a4 12.0
8 a2:a4 0.211
9 a2:a3 0.305
10 Residuals 4.88
如何添加5-9行并将其添加到新行中并删除原始行?
所需的输出?
term sumsq
<chr> <dbl>
1 a1 10.1
2 a2 5.15
3 a3 45.1
4 a4 7.32
5 Interactions 27.486
10 Residuals 4.88
注意:0.870+14.1+12.0+0.211+0.305=27.486
df %>%
slice(., 5:9)
答案 0 :(得分:1)
我们可以将数据分为第5行和第9行以及其他所有两部分。我们采用第二部分的sum
并将其添加到第一部分。
library(dplyr)
df %>%
slice(-(5:9)) %>%
bind_rows(df %>%
slice(5:9) %>%
summarise(term = "Interaction",
sumsq = sum(sumsq)))
# term sumsq
#1 a1 10.100
#2 a2 5.150
#3 a3 45.100
#4 a4 7.320
#5 Residuals 4.880
#6 Interaction 27.486
与基数R类似
rbind(df[-c(5:9), ], data.frame(term = "Interaction", sumsq = sum(df$sumsq[5:9])))