Counting common rows from multiple data frames

I have several data frames, as shown below, with a unique identifier for each row. I am trying to find common rows and create a new data frame that appears in at least two data frames.

example-row with Id = 2 appears in all three data frames. similarly, the line with Id = 3 is in df1 and df3.

I want to create a loop that can find shared rows and create a new data frame with shared rows.

df1 <- data.frame(Id=c(1,2,3,4),a=c(0,1,0,2),b=c(1,0,1,0),c=c(0,0,4,0)) 
df2 <- data.frame(Id=c(7,2,5,9),a=c(4,1,9,2),b=c(1,0,1,5),c=c(3,0,7,0))
df3 <- data.frame(Id=c(5,3,2,6),a=c(9,0,1,5),b=c(1,1,0,0),c=c(7,4,0,0)) 

> df1                   > df2 
 Id | a | b | c |         Id | a | b | c |
 ---|---|---|---|         ---|---|---|---|                  
  1 | 0 | 1 | 0 |          7 | 4 | 1 | 3 |                           
 ---|---|---|---|         ---|---|---|---|                  
  2 | 1 | 0 | 0 |          2 | 1 | 0 | 0 |
 ---|---|---|---|         ---|---|---|---|
  3 | 0 | 1 | 4 |          5 | 9 | 1 | 7 |
 ---|---|---|---|         ---|---|---|---|
  4 | 2 | 0 | 0 |          9 | 2 | 5 | 0 |

 > df3
 Id | a | b | c |
 ---|---|---|---|
  5 | 9 | 1 | 7 |
 ---|---|---|---|
  3 | 0 | 1 | 4 |
 ---|---|---|---|
  2 | 1 | 0 | 0 |
 ---|---|---|---|
  6 | 5 | 0 | 0 |

> expected_output
 Id | a | b | c |
 ---|---|---|---|
  5 | 9 | 1 | 7 |
 ---|---|---|---|
  3 | 0 | 1 | 4 |
 ---|---|---|---|
  2 | 1 | 0 | 0 |
 ---|---|---|---|

Note: - The identifier is unique. In addition, I want to remove rows from the original data that are duplicated, and I use it to create a new framework.

+4
source share
2

, , . , , , .

, :

library(data.table)

DTs = lapply(list(df1,df2,df3), data.table)

Id_keep = rbindlist(lapply(DTs, `[`, j = "Id"))[, .N, by=Id][N >= 2L, Id]

DT_keep = Reduce(funion, DTs)[Id %in% Id_keep]

#    Id a b c
# 1:  2 1 0 0
# 2:  3 0 1 4
# 3:  5 9 1 7

DTs , .

, , ,

  • list(df1,df2,df3)
  • lapply(DTs, `[`, j = "Id")
  • Reduce(funion, DTs)

, , ?lapply, ?rbindlist, ?funion.

+2

:

combined <- rbind(df1, df2, df3)

:

duplicate_rows <- unique(combined[duplicated(combined), ])

(duplicated(combined) )

+1

Source: https://habr.com/ru/post/1682527/


All Articles