selecting rows according to all covariates combinations of a different dataframe

落爺英雄遲暮 提交于 2019-12-12 05:20:05

问题


I am currently trying to figure out how to select all the rows of a long dataframe (long) that present the same x1 and x2 combinations characterizing another dataframe (short).

The simplified data are:

long <- read.table(text = "
  id_type   x1   x2

   1       0     0  
   1       0     1
   1       1     0
   1       1     1
   2       0     0
   2       0     1
   2       1     0
   2       1     1
   3       0     0  
   3       0     1
   3       1     0
   3       1     1
   4       0     0  
   4       0     1
   4       1     0
   4       1     1", 
header=TRUE) 

and

short <- read.table(text = "
   x1   x2    

   0     0    
   0     1", 
     header=TRUE) 

The expected output would be:

 id_type  x1    x2

   1       0     0  
   1       0     1
   2       0     0
   2       0     1
   3       0     0  
   3       0     1
   4       0     0  
   4       0     1

I have tried to use:

out <- long[unique(long[,c("x1", "x2")]) %in% unique(short[,c("x1", "x2")]), ] 

but the %in% adoption is used wrongly here.. thank you very much for any help!


回答1:


You are requesting an inner join:

> merge(long, short)
  x1 x2 id_type
1  0  0       1
2  0  0       2
3  0  0       3
4  0  0       4
5  0  1       1
6  0  1       2
7  0  1       3
8  0  1       4


来源:https://stackoverflow.com/questions/14441028/selecting-rows-according-to-all-covariates-combinations-of-a-different-dataframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!