How to find if ANY column has a specific value I am looking for?

后端 未结 5 623
我在风中等你
我在风中等你 2021-01-18 20:56
   id first  middle  last       Age
    1 Carol  Jenny   Smith      15
    2 Sarah  Carol   Roberts    20
    3 Josh   David   Richardson 22

I am t

5条回答
  •  情书的邮戳
    2021-01-18 21:33

    We can use rowSums

    df$Carol <- as.integer(rowSums(df[2:4] == "Carol") > 0)
    
    df
    #  id first middle       last Age Carol
    #1  1 Carol  Jenny      Smith  15     1
    #2  2 Sarah  Carol    Roberts  20     1
    #3  3  Josh  David Richardson  22     0
    

    If we need it as a function

    fun <- function(df, value) {
       as.integer(rowSums(df[2:4] == value) > 0)
    }
    
    fun(df, "Carol")
    #[1] 1 1 0
    fun(df, "Sarah")
    #[1] 0 1 0
    

    but this assumes the columns you want to search are at position 2:4.

    To give more flexibility with column position

    fun <- function(df, cols, value) {
       as.integer(rowSums(df[cols] == value) > 0)
     }
    fun(df, c("first", "last","middle"), "Carol")
    #[1] 1 1 0
    fun(df, c("first", "last","middle"), "Sarah")
    #[1] 0 1 0
    

提交回复
热议问题