How to programatically compare an entire row in R?

前端 未结 3 1901
暖寄归人
暖寄归人 2021-01-23 10:26

I have the following dataframe in R:
data= Time X1 X2 X3 1 1 0 0 2 1 1 1 3 0 0 1 4 1 1 1 5 0 0 0 6 0 1 1 7 1 1 1 8 0 0

3条回答
  •  醉话见心
    2021-01-23 10:47

    Here's a couple of options using a merge:

    merge(list(X1=0,X2=1,X3=1), dat)
    #or
    merge(setNames(list(0,1,1),c("X1","X2","X3")), dat)
    

    Or even using positional indexes based on what columns you want matched up:

    L <- list(0,1,1)
    merge(L, dat, by.x=seq_along(L), by.y=2:4)
    

    All of which return:

    #  X1 X2 X3 Time
    #1  0  1  1    6
    

    If your matching variables are all of the same type, you could also safely do it via matrix comparison like:

    dat[colSums(t(dat[c("X1","X2","X3")]) == c(0,1,1)) == 3,]
    

提交回复
热议问题