Search and find values row-wise a dataframe

后端 未结 4 1974
后悔当初
后悔当初 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

    Since you don't want a loop, you could get creative and paste the columns together by row, and then use grepl to compare it with vec

    > as.numeric(grepl(paste(vec, collapse="|"), do.call(paste, df)))
    [1] 1 0 1 0 
    

    Here's a second option that compares the rows to the unlisted data frame

    > as.numeric(seq(nrow(df)) %in% row(df)[unlist(df) %in% vec])
    [1] 1 0 1 0
    

提交回复
热议问题