[R] identifying when one element of a row has a positive number
peter.langfelder at gmail.com
Thu Jan 27 07:05:08 CET 2011
Here's a solution., maybe not the most elegant but works.
df.r = df1[, c(3:5)]; # restricted data
nNonZero = apply(df.r!=0, 1, sum);
one = nNonZero==1;
oneZero = nNonZero==2;
whichOne = apply(df.r[one, ]!=0, 1, which);
whichZero = apply(df.r[oneZero, ]==0, 1, which);
colNames = colnames(df.r);
one_presence = one_absence = rep(NA, nrow(df1))
one_presence[one] = colNames[whichOne];
one_absence[oneZero] = colNames[whichZero];
On Wed, Jan 26, 2011 at 9:36 PM, Daisy Englert Duursma
<daisy.duursma at gmail.com> wrote:
> I am not sure where to begin with this problem or what to search for
> in r-help. I just don't know what to call this.
> If I have 5 columns, the first 2 are the x,y, locations and the last
> three are variables about those locations.
> What I would like to produce is an additional column that tells when
> only 1 of the three variables has a value greater than 0. I would like
> this new column to give the name of the variable. Likewise, I would
> like a column that tells one only one of the three variables for a
> given row has a value of 0. For my example the new columns would be:
> The end result should look like
> I am sure I can do this with a loop or maybe grep but I am out of ideas.
> Any help would be appreciated.
> Daisy Englert Duursma
> Room E8C156
> Dept. Biological Sciences
> Macquarie University NSW 2109
> R-help at r-project.org mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help