首页 > 解决方案 > 合并两个表对象以便在 r 中创建一个新的数据框

问题描述

我有 2 个表对象,例如:

类型1:

   0    1    2    3   12   20 
1318  841    4    1    1    1


type1<- structure(c(`0` = 1318L, `1` = 841L, `2` = 4L, `3` = 1L, `12` = 1L, 
`20` = 1L), .Dim = 6L, .Dimnames = structure(list(c("0", "1", 
"2", "3", "12", "20")), .Names = ""), class = "table")

类型2:

  0   1   2  12  15 
 93 178   1   4   1



type2<-structure(c(`0` = 93L, `1` = 178L, `2` = 1L, `12` = 4L, `15` = 1L
), .Dim = 5L, .Dimnames = structure(list(c("0", "1", "2", "12", 
"15")), .Names = ""), class = "table")

我想合并它们以获得数据框,例如:

x  y2     y
1  type1  841
2  type1  4
3  type1  1
4  type1  0
5+ type1  2
1  type2  178
2  type2  1
3  type2  0
4  type2  0
5+ type2  5

我将 type1 或 type2 中的所有列相加>= 5,并将此计数添加到5+行中。

有人有想法吗?

标签: rdplyrdatatable

解决方案


我会这样做(绑定然后......):

library(dplyr)
rbind(data.frame(y = type1, y2 = "type1"), data.frame(y = type2, y2 = "type2")) %>% 
  mutate(x = ifelse(as.numeric(as.character(y.Var1)) < 5, as.character(y.Var1), "5+")) %>% 
  group_by(x,y2) %>% 
  summarise(y = sum(y.Freq), .groups = "drop") %>% 
  arrange(y2, desc(y)) 
# A tibble: 9 × 3
  x     y2        y
  <chr> <chr> <int>
1 0     type1  1318
2 1     type1   841
3 2     type1     4
4 5+    type1     2
5 3     type1     1
6 1     type2   178
7 0     type2    93
8 5+    type2     5
9 2     type2     1

推荐阅读