Search and find values row-wise a dataframe

后端 未结 4 1982
后悔当初
后悔当初 2021-01-06 11:00

My dataframe looks like this:

x1 <- c(\"a\", \"c\", \"f\", \"j\")
x2 <- c(\"b\", \"c\", \"g\", \"k\")
x3 <- c(\"b\", \"d\", \"h\", NA)
x4 <- c(\"         


        
4条回答
  •  天涯浪人
    2021-01-06 11:22

    Here's one way to do this:

    df$valueFound <- apply(df,1,function(x){
      if(any(x %in% vec)){ 
        1 
      } else {
        0
      }
    })
    ##
    > df
      x1 x2   x3   x4 valueFound
    1  a  b    b    a          1
    2  c  c    d    e          0
    3  f  g    h    i          1
    4  j  k            0
    

    Thanks to @David Arenburg and @CathG, a couple of more concise approaches:

    • apply(df, 1, function(x) any(x %in% vec) + 0)
    • apply(df, 1, function(x) as.numeric(any(x %in% vec)))

    Just for fun, a couple of other interesting variants:

    • apply(df, 1, function(x) any(x %in% vec) %/% TRUE)
    • apply(df, 1, function(x) cumprod(any(x %in% vec)))

提交回复
热议问题