Warm tip: This article is reproduced from stackoverflow.com, please click
r

How to count occurrence of a value across multiple data frames

发布于 2020-03-27 10:15:21

I have some dataframes which look like this:

df1 <- data.frame(Id=c(1,2,3,4),a=c(66,64,54,65)) 
df2 <- data.frame(Id=c(2,7,4,6),a=c(70,74,71,54))
df3 <- data.frame(Id=c(9,11,1,2),a=c(67,53,55,73))

df1

  Id  a
1  1 66
2  2 64
3  3 54
4  4 65

df2
  Id  a
1  2 70
2  7 74
3  4 71
4  6 54

df3
   Id  a
 1  9 67
 2 11 53
 3  1 55
 4  2 73

I would like to know what code would allow me to calculate the occurrence of each ID value across all three data-frames.

My ideal output looks like this:

 ID  Count
  1    2
  2    3
  3    1
  4    2
  7    1
  6    1
  9    1
  11   1
Questioner
T.2001
Viewed
159
akrun 2019-07-03 21:43

We can use rbindlist

library(data.table)
rbindlist(mget(paste0("df", 1:3)))[, .N, Id]\
#   Id N
#1:  1 2
#2:  2 3
#3:  3 1
#4:  4 2
#5:  7 1
#6:  6 1
#7:  9 1
#8: 11 1