How to programatically compare an entire row in R?

前端 未结 3 1899
暖寄归人
暖寄归人 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,]
    
    0 讨论(0)
  • 2021-01-23 10:49

    apply(data, 1, function(x) all(x==c(0,1,1)))

    This will go down each row of the frame and return TRUE for each row where the row is equal to c(0,1,1).

    0 讨论(0)
  • 2021-01-23 11:08

    this is your data

    mydf <- structure(list(Time = 1:10, X1 = c(1L, 1L, 0L, 1L, 0L, 0L, 1L, 
    0L, 1L, 0L), X2 = c(0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 0L), 
        X3 = c(0L, 1L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 0L)), .Names = c("Time", 
    "X1", "X2", "X3"), class = "data.frame", row.names = c(NA, -10L
    ))
    

    Using subset

    subset(mydf, X1 == 0 & X2==1 & X3==1)
    #  Time X1 X2 X3
    #6    6  0  1  1
    

    another way

    mydf[mydf$X1 ==0 & mydf$X2 ==1 & mydf$X3 ==1, ] 
    #   Time X1 X2 X3
    #6    6  0  1  1
    

    or like this

    mydf[mydf$X1 ==0 & mydf$X2 & mydf$X3 %in% c(1,1), ]
    #  Time X1 X2 X3
    #6    6  0  1  1
    

    you can also do that by

    library(dplyr)
    filter(mydf, X1==0 & X2==1 & X3==1)
    #   Time X1 X2 X3
    #1    6  0  1  1
    
    0 讨论(0)
提交回复
热议问题