r - 合并两个表对象以便在 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+
行中。
有人有想法吗?
解决方案
我会这样做(绑定然后......):
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
推荐阅读
- reactjs - 反应输入 minLength onKeyDown
- mips - 按顺序排列的 MIPS 阵列
- angular - 无法在包含无效搜索数据的表上显示错误消息(没有来自 API 的数据,给出 404)
- javascript - 在 javascript 中使用原型的主要优点是什么?
- python - Django Post Save Signal 继续循环
- python - 如何在 Python 中打印带有文本的变量?
- android - 我们可以在 Android 中不使用 DrawerLayout 来制作导航抽屉吗?
- python - Windows 商店的 python 版本或将 python 安装到程序文件是否具有受限权限?
- azure-resource-manager - 如何使用 Pulumi Azure Native 将 WebAppAzureStorageAccounts 连接到 WebApp
- spring - 覆盖泛型类的杰克逊属性