在 R 中使用 sum 和 table summary 转换两个子图块

Transform two subtiles using sum and table summary in R

我有两个列表,例如 ;

type1 0 0 0 0 0 2 5 5 5 1 1 3
type2 0 0 0 0 0 1 5 2 3 0 0 1

这里是输出格式,如果有帮助的话:

list(type1 = c(0,0,0,0,0,2,5,5,5,1,1,3), 
     type2 = c(0,0,0,0,0,1,5,2,3,0,0,1))

我想将其转换为数据框,例如:

Nb type   Value
1  type1  2
2  type1  1
3  type1  1
4  type1  0
5+ type1  3
1  type2  0
2  type2  1
3  type2  1
4  type2  0
5+ type2  10

其中 df$type==type1 对应于 Nb 1,2,3,4 或 >=5 的数量 其中 df$type==type 对应于 type1 列表中 Nb 1,2,3,4 or >=5 的总和数.


例如: 在 type1 中,我们看到 3 个数字 >=5,然后我得到了这一行:

Nb type   Value
5+ type1  3

,在这 3 个中,我加上 type2 的总和,即 5+2+3 = 10,然后我添加:

Nb type   Value
5+ type1  3
5+ typ2   10 

有人有想法吗?

一个选项是在转换为 factor 后在 'type1' 元素上获取 table,其中 levels 指定为 0 到 5,按总和进行分组'type2' 元素,其中组是 'type1' 元素,stack 它们分为两列 data.frame,并添加 'type' 列以及 rbind list 个元素

out <- do.call(rbind, Map(cbind, type = names(list1), lapply(setNames(list(table(factor(list1$type1, levels = 0:5)), tapply(list1$type2, factor(list1$type1, levels = 0:5), FUN = function(x) sum(x, na.rm = TRUE))), names(list1)), stack))
)
row.names(out) <- NULL
out$values[is.na(out$values)] <- 0
subset(out[c(3, 1, 2)], ind != 0)

-输出

   ind  type values
2    1 type1      2
3    2 type1      1
4    3 type1      1
5    4 type1      0
6    5 type1      3
8    1 type2      0
9    2 type2      1
10   3 type2      1
11   4 type2      0
12   5 type2     10

或使用forcats

library(forcats)
library(dplyr)
grp <- factor(with(list1, fct_collapse(as.character(type1), 
       `>=5` = as.character(type1)[type1 >=5])), levels = c(0:4, ">=5"))
v1 <- table(grp)
v2 <- tapply(list1$type2, grp, FUN = sum)
bind_rows(list(type1 = stack(v1)[2:1], type2 = stack(v2)[2:1]), .id = 'type') %>% 
     filter(ind != '0')