r - Is a value present in certain columns of a dataframe (by row)? Using %in% and | on multiple columns works, but is there a more concise way? -
i have dataframe looks like
> df = data.frame(c1=c(3,6,na,5), c2=c(2,na,3,na), c3=c(1,4,4,2)) > df c1 c2 c3 1 3 2 1 2 6 na 4 3 na 3 4 4 5 na 2
i create additional columns record, each row, whether given value present in c1 or c2, ignoring c3.
this works not concise (especially actual data):
> df$is.2.in.c1.or.c2[df$c1 %in% 2 | df$c2 %in% 2] = 'it there' > df c1 c2 c3 is.2.in.c1.or.c2 1 3 2 1 there 2 6 na 4 <na> 3 na 3 4 <na> 4 5 na 2 <na>
is there more concise way?
we can try rowsums
after creating logical matrix using ==
.
i1 <- rowsums(df[1:2]==2, na.rm=true)!=0
it better have logical index ('i1') instead of flagging 'it there'. but, if needed,
ifelse(i1, 'it there', na) #[1] "it there" na na na
Comments
Post a Comment