转置汇总表

时间:2018-06-29 05:33:11

标签: r

我在文本文件中有一个具有以下格式的表:

enter image description here

我需要转置它,使其看起来像这样:

enter image description here

在R中有一种简单的方法吗?

3 个答案:

答案 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::dcastdplyr::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中的addmarginsbase 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))