Selecting rows based on values in other table
Probably a beginner-question. I can't select a row based on criteria from other table. Should be simple, but I'm missing something.
I have two tables:
T1
X C
3 a
4 a
4开发者_C百科1 b
and
T2
A B C D
1 5 a 22
7 11 a 27
35 49 b 29
I want to add the column D to T1, where X is between A and B in T2, and C=C. So the resulting table should look like this:
T1b
X C D
3 a 22
4 a 22
41 b 29
Thanks.
/Chris
This is one solution.
Import the data:
> con <- textConnection("X C
+ 3 a
+ 4 a
+ 41 b")
> T1 <- read.table(con, sep=" ", header=TRUE)
> close(con)
> con <- textConnection("A B C D
+ 1 5 a 22
+ 7 11 a 27
+ 35 49 b 29")
> T2 <- read.table(con, sep=" ", header=TRUE)
> close(con)
Now merge and subset:
> T3 <- merge(T1, T2)
> T3[T3$X > T3$A & T3$X < T3$B, c("X", "C", "D")]
X C D
1 3 a 22
3 4 a 22
5 41 b 29
精彩评论