首页 > 解决方案 > How to find rows IDs that a value exists in any of column in R and then put Exists to a new dataframe

问题描述

want to find to which rows but in any column,there is a dataframe

标签: r

解决方案


One option is rowSums on a logical matrix created with ==, then convert it to a logical vector with > 0, wrap with which to return the row index where atleast one column have 'citrus fruit' value. Use that index to change the value in 'newcol' of the dataset 'groc' to 'exists'

i1 <- which(rowSums(A == 'citrus fruit') > 0)
groc$newcol[i1] <- 'exists'

data

set.seed(24)
A <- data.frame(col1 = c('citrus fruit', 'a', 'b'), col2 = c('a', 'b',
       'citrus fruit'), stringsAsFactors = FALSE)
groc <- data.frame(value = rnorm(3))

推荐阅读