[R] Another newbie question

jim holtman jholtman at gmail.com
Wed Jan 7 20:42:00 CET 2009


You did not provide any data, so I will take a guess at what it looks like:

> x <- matrix(sample(0:1, 100, TRUE), 10)
> colnames(x) <- LETTERS[1:10]
> x <- as.data.frame(x)
> x
   A B C D E F G H I J
1  0 1 0 0 0 1 1 0 0 0
2  0 0 0 0 1 1 0 0 1 0
3  1 1 0 0 1 0 0 0 1 1
4  0 1 1 1 0 1 1 0 0 0
5  0 1 1 0 0 0 1 0 0 1
6  1 0 1 1 0 0 0 0 0 1
7  1 1 0 1 0 0 0 0 0 0
8  0 1 0 1 0 0 1 0 0 0
9  0 1 0 0 0 0 1 0 0 0
10 1 0 1 0 1 1 0 1 0 1
> x$match <- apply(x, 1, function(z) paste(colnames(x)[z == 1], collapse=","))
>
>
> x
   A B C D E F G H I J       match
1  0 1 0 0 0 1 1 0 0 0       B,F,G
2  0 0 0 0 1 1 0 0 1 0       E,F,I
3  1 1 0 0 1 0 0 0 1 1   A,B,E,I,J
4  0 1 1 1 0 1 1 0 0 0   B,C,D,F,G
5  0 1 1 0 0 0 1 0 0 1     B,C,G,J
6  1 0 1 1 0 0 0 0 0 1     A,C,D,J
7  1 1 0 1 0 0 0 0 0 0       A,B,D
8  0 1 0 1 0 0 1 0 0 0       B,D,G
9  0 1 0 0 0 0 1 0 0 0         B,G
10 1 0 1 0 1 1 0 1 0 1 A,C,E,F,H,J
>


On Wed, Jan 7, 2009 at 1:28 PM, AllenL <allen.larocque at gmail.com> wrote:
>
> Problem:
> I have a data frame with 1s and 0s denoting presence/absence of species
> (columns) for particular plot measurements (rows). What I want to do is make
> a new column whose entries for each row is a list of the column names in
> which a species is present (ie. for row one its entry might read:
> "sp1","sp2", etc.). I've tried various functions etc. but can't seem to get
> the syntax right/ the correct combination of functions.
> Thanks in advance!
> -Allen
>
> --
> View this message in context: http://www.nabble.com/Another-newbie-question-tp21337371p21337371.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list