答案 0 :(得分:2)
library(tidyverse)
df1%>%
spread(species,count)%>%
rbind(c(status="Total",colSums(.[-1])))
status A B C
1 Alive 37 6 13
2 Dead 17 0 11
3 Total 54 6 24
要使该类保持数字形式,可以执行以下操作:
df1%>%
spread(species,count)%>%
rbind(cbind.data.frame(status="Total",t(colSums(.[-1]))))
status A B C
1 Alive 37 6 13
2 Dead 17 0 11
3 Total 54 6 24
答案 1 :(得分:2)
使用reshape2::dcast
和dplyr::summarise_at
的解决方案可以通过更改wide-format
中的数据,然后与摘要行绑定以包含Total
来实现。解决方案将为:
library(tidyverse)
library(reshape2)
dcast(df, status~species, value.var = "count") %>%
bind_rows(c(status = "Total",summarise_at(.,vars(A:C), funs(sum))))
# status A B C
# 1 Alive 37 6 13
# 2 Dead 17 0 11
# 3 Total 54 6 24
数据:
df <- read.table(text="
species status count
A Dead 17
A Alive 37
B Dead 0
B Alive 6
C Dead 11
C Alive 13",
header = TRUE, stringsAsFactors = FALSE)
答案 2 :(得分:1)
我们可以将xtabs
中的addmargins
与base R
一起使用
addmargins(xtabs(count ~ status + species, df), 1)
# species
#status A B C
# Alive 37 6 13
# Dead 17 0 11
# Sum 54 6 24
df <- structure(list(species = c("A", "A", "B", "B", "C", "C"),
status = c("Dead",
"Alive", "Dead", "Alive", "Dead", "Alive"), count = c(17L, 37L,
0L, 6L, 11L, 13L)), .Names = c("species", "status", "count"),
class = "data.frame", row.names = c(NA, -6L))