the rules of subsetting

后端 未结 1 1201
暖寄归人
暖寄归人 2020-12-10 18:30

Having df1 and df2 as follows:

df1 <- read.table(text =\" x y z
                          1 1 1
                          1 2 1
         


        
相关标签:
1条回答
  • 2020-12-10 19:05

    In addition to your nice solution using merge (thanks for that, I always forget merge), this can be achieved in base using ?interaction as follows. There may be other variations of this, but this is the one I am familiar with:

    > df1[interaction(df1) %in% interaction(df2), ]
    

    Now to answer your question: First, I think there's a typo (corrected) in:

    df1[ df1$z %in% df2$c | df2$b == 9,] # second part should be df2$b == 9
    

    You would get an error, because the first part evaluates to

    [1] TRUE TRUE TRUE TRUE TRUE
    

    and the second evaluates to:

    [1] FALSE FALSE FALSE FALSE
    

    You do a | operation on unequal lengths getting the error:

    longer object length is not a multiple of shorter object length
    

    Edit: If you have multiple columns then you can choose the interaction as such. For example, if you want to get from df1 the rows where the first two columns match with that of df2, then you could simply do:

    > df1[interaction(df1[, 1:2]) %in% interaction(df2[, 1:2]), ]
    
    0 讨论(0)
提交回复
热议问题