Leave only those rows in matrices which have equal elements at certain column

前端 未结 4 1101
一向
一向 2021-01-28 00:56

Let me show an example. Consider we have 3 tables (focus on columns N):

   Table 1         Table 2        Table 3
-------------   -------------   -------------
           


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-28 01:21

    Use a set intersection to find the common values of N amongst all the tables

    > t1 <-data.frame(N=c(5,10,15),Values=c(1,2,3))
    > t2 <-data.frame(N=c(5,6,10,15),Values=c(-1,-2,-3,-4))
    > t3 <-data.frame(N=c(5,6,10,12,15),Values=c(1,21,5,6,3))
    > common<-intersect(intersect(t1$N,t2$N),t3$N)
    > common
    [1]  5 10 15
    

    Then just subset each table to find the rows with those common values

    > newt1<-t1[t1$N %in% common,]
    > newt2<-t2[t2$N %in% common,]
    > newt3<-t3[t3$N %in% common,]
    > newt3
       N Values
    1  5      1
    3 10      5
    5 15      3
    

    This approach should scale such that you can create a function and pass in a vector of data frames and a column name. It can return a vector of new data frames.

    I've used data frames. The same approach will work with matrices

提交回复
热议问题