r - How to combine contents of two frequency tables into one frequency table in R?
问题描述
I had a question about how to combine two frequency tables into one frequency table.
So if I have 2 tables:
table1:
Col1
18
19
17
19
13
19
table2:
Col1
18
19
12
15
18
I'd like to make a 3rd table, table3
such that table3$"Col2"
counts the number of times a number in table3$"Col1"
appears in table1$"Col1"
and such that table3$"Col3"
counts the number of times a number in table3$"Col1"
appears in table2$"Col1"
table3$"Col1"
is a list of all elements in table1$"Col1"
and in table2$"Col2"
table3:
Col1 Col2 Col3
12 0 1
13 1 0
15 0 1
17 1 0
18 1 2
19 3 1
I originally tried doing this:
table3$"Col1"<-table(table1$"Col1",table2$"Col1")
but it doesn't work because table1$"Col1"
and table2$"Col1"
have different lengths:
Error in table(table1$"Col1", table2$"Col1") : all arguments must have the same length
解决方案
这是另一种选择:
f <-function(x,y) sum(x %in% y)
V1 <- sort(unique(c(table1$'Col1', table2$'Col1')))
V2 <- sapply(V1,f,x = Col1)
V3 <- sapply(V1,f,x = Col2)
> data.frame(V1,V2,V3)
V1 V2 V3
1 12 0 1
2 13 1 0
3 15 0 1
4 17 1 0
5 18 1 2
6 19 3 1
推荐阅读
- istio - 我可以在不启用 Istio mTLS 的情况下在服务服务调用案例中使用 K8S ServiceAccount 对服务客户端进行身份验证吗?
- c# - 将字符串数组转换为多维双精度
- python - 如何注释(xy 坐标)nd.array 的百分位图?
- ruby-on-rails - 无法使用“accepts_nested_attributes_for”创建关联/嵌套子记录
- bash - 如何检测 tmux 是否附加到 bash 中的会话?
- c++ - OpenGL显示白框,而不是立方体
- javascript - 如何使用javascript显示变量值?
- java - JavaFX,用鼠标选择和移动画布图像
- python - 尝试在 Python 2.7 中导入任何模块时,如何解决“NameError: name 'null' is not defined”错误
- wpf - 计算网格中的列数