r - Finding the Column Index for a Specific Value -


i having brain cramp. below toy dataset:

df <- data.frame(         id = 1:6,          v1 = c("a", "a", "c", na, "g", "h"),         v2 = c("z", "y", "a", na, "a", "g"),         stringsasfactors=f) 

i have specific value want find across set of defined columns , want identify position located in. fields searching characters , trick value looking might not exist. in addition, null strings present in dataset.

assuming knew how this, variable position indicates values returned.

> df   id   v1   v2 position 1  1       z        1 2  2       y        1 3  3    c           2 4  4 <na> <na>       99 5  5    g           2 6  6    h    g       99 

the general rule want find position of value "a", , if not located or if v1 missing, want 99 returned.

in instance, searching across v1 , v2, in reality, have 10 different variables. worth noting value searching can exist once across 10 variables.

what best way generate recode?

many in advance.

use match:

> df$position <- apply(df,1,function(x) match('a',x[-1], nomatch=99 )) > df   id   v1   v2 position 1  1       z        1 2  2       y        1 3  3    c           2 4  4 <na> <na>       99 5  5    g           2 6  6    h    g       99 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -