2014-09-11 48 views
-3

假設有兩個2數據集,並且用戶想從第一個獲得所有行,並且在第二個數據集中。R:根據第二個數據的列子集data.frame

第一數據集是mtcars和第二爲「數據」是這樣的(用於演示目的,假設大套)

data <- data.frame(colA=c(4,4,4,4,4,4,4,6,6),colB='foo') 

如何在dplyr或鹼RI可以達到相同的結果,與此SQL命令:

sqldf("select * from mtcars where cyl in (select distinct colA from data)") 

想象兩個數據集都有超過10萬行!所以dplyr和快速解決方案是首選。

正確的結果是

> sqldf("select * from mtcars where cyl in (select distinct colA from data)") 
    mpg cyl disp hp drat wt qsec vs am gear carb 
1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 
2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 
3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 
4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 
5 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 
6 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 
7 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 
8 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 
9 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 
10 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 
11 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 
12 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 
13 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 
14 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 
15 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 
16 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 
17 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 
18 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2 
+1

是'mtcars [1:以%數據[1],nrow(mtcars)%]''在mtcars' rownames不是數字 – akrun 2014-09-11 12:56:31

+0

假設兩列都是字符串或需要轉換爲字符串 – userJT 2014-09-11 13:11:53

+1

爲什麼不簡單地說:'mtcars [mtcars $ cyl%in%unique(data $ colA),]'? – zx8754 2014-09-11 13:20:47

回答

2

使用dplyr

library(dplyr) 
mtcars %>% filter(cyl %in% data[,1]) 
+0

它應該列出來自mtcars的所有行,其中柱面爲4或6.正確的結果有更多的行。 – userJT 2014-09-11 13:13:53

+0

@ user56再試一次,回答編輯。 – zx8754 2014-09-11 13:24:59

+1

@ zx8754感謝您的編輯。我不在。 – akrun 2014-09-11 14:35:33