selecting rows according to all covariates combina

2019-08-31 02:30发布

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!

标签: r subset
1条回答
混吃等死
2楼-- · 2019-08-31 03:01

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
查看更多
登录 后发表回答