data frame condition multiple rows

Viewed 71

Say one has a data frame as follows:

data <- data.frame('obs' = c('a','c','b'), 'top1' = c('a','b','c'), 'top2' = c('b', 'c', 'f'), 'top3' = c('g', 'h', 'd'))

I wan to compute a new column topn which is a conditional that works in the following fashion: if the value of obs is in any of the top columns then topn should be equal to obs, otherwise topn can be assigned any value, say top1. Of course I know I can do this with an or and ifelse, but I'm looking for a shorter way to write it because in my table I can have up to 10 top columns.

 obs top1 top2 top3 topn
   a    a    b    g  a
   c    b    c    h  c
   b    c    f    d  c
2 Answers

If we are looking for a vectorized approach, then we can use the rowSums on a logical matrix to find if there are any matches, then with ifelse get the column values based on the logical vector

i1 <- data[-1] == data['obs'][col(data[-1])]
data$topn <- ifelse(rowSums(i1) != 0, as.character(data$obs), as.character(data$top1))
data$topn
#[1] "a" "c" "c"

This might be helpful and quick.

f=function(a){

if(a[1] %in% a[-1]){

    return (a[1])
  }

else{sample(a[-1],1)}

}

data$topn=apply(data,1,f)

Related