首页 > 解决方案 > 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

标签: rdata.table

解决方案


这是另一种选择:

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

推荐阅读