1

I have a dataset as follows (in data.frame format):

>dataset
X Y Z Value
a c f 12
a d f 45
a c f 654
a d g 684
a c g 54
b d f 78
b c f 31
b d f 777
b c g 54 
b d g 45

And I have an second data.frame with criteria:

>criteria
X Y Z 
a c f 
b d f 

How do I apply the second matrix to the first to get, in this example, c(654, 12, 777, 68) as a result? Most of the things I've tried end up pulling out all the lines with any of the three variables matching instead of all three.

EDIT: Fixed what the result is supposed to be

user79928
  • 11
  • 3

3 Answers3

3

Just use merge:

merge(df1, df2)

If you want just the vector:

merge(df1, df2)[,'Value']

Data:

df1 <- read.table(text = 
'X Y Z Value
a c f 12
a d f 45
a c f 654
a d g 684
a c g 54
b d f 78
b c f 31
b d f 777
b c g 54 
b d g 45', h = T)

df2 <- read.table(text = '
X Y Z 
a c f 
b d f', h = T)
Paulo MiraMor
  • 1,582
  • 12
  • 30
0

adding some points on y logic :

do.call(paste0, criteria)
# [1] "acf" "bdf"
do.call(paste0, dataset[1:3])
# [1] "acf" "adf" "acf" "adg" "acg" "bdf" "bcf" "bdf" "bcg" "bdg"
v = do.call(paste0, dataset[1:3]) %in% do.call(paste0, criteria)
# [1]  TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE FALSE

Now this logical vector is used to subset the Value column

dataset$Value[v]
# [1]  12 654  78 777
joel.wilson
  • 8,243
  • 5
  • 28
  • 48
  • why did i get a downvote?? mind explaining that whoever did it? – joel.wilson Feb 03 '17 at 20:39
  • 2
    Not my downvote, but this seems like a hacky way to do an inner join. I think Paulo's "just use merge" answer is spot on. – Gregor Thomas Feb 03 '17 at 21:55
  • @joel.wilson "_why did i get a downvote??_" I'm not the one who downvoted it, but it's probably because code-only answers are low quality. Please edit to add some context. – Donald Duck Feb 04 '17 at 08:51
  • @DonaldDuck do you think is the reason for downvote...i don't think so.. anyway i shall keep in mind your point too! updated my answe – joel.wilson Feb 04 '17 at 09:14
0

We can use the tidyverse

library(tidyverse)
inner_join(df1, df2) %>%
             select(Value)
akrun
  • 874,273
  • 37
  • 540
  • 662