Message-ID: <CAAxdm-5tp_65MbrfeS3Wxvzx-ePMT+HndWSakMG-=RAB2C67aA@mail.gmail.com>
Date: 2011-12-26T01:38:32Z
From: jim holtman
Subject: Recoding multiple TRUE/FALSE columns into a single list of TRUE columns
In-Reply-To: <000001ccc365$a88ae590$f9a0b0b0$@edu>
Try this:
> x <- read.table(text = " P1 P2 P3 P4
+ 1 0 0 1 1
+ 2 0 1 1 1
+ 3 1 0 0 0
+ 4 0 0 0 0
+ 5 1 1 1 1 ", header = TRUE)
> labs <- apply(x, 1, function(.row){
+ indx <- which(.row == 1)
+ if (length(indx) > 0) return(paste(names(x)[indx], collapse = ','))
+ else return(NA)
+ })
> x$result <- labs
> x
P1 P2 P3 P4 result
1 0 0 1 1 P3,P4
2 0 1 1 1 P2,P3,P4
3 1 0 0 0 P1
4 0 0 0 0 <NA>
5 1 1 1 1 P1,P2,P3,P4
>
On Sun, Dec 25, 2011 at 7:30 PM, David Epstein <davideps at umich.edu> wrote:
> Hi everyone,
>
> I need to recode multiple columns in a dataframe into a single column in a
> variety of different ways. ?Often the values will be TRUE/FALSE and I want a
> list of the columns that are true as in the Result column below:
>
> ? ?P1 ? P2 ? P3 ? P4 ? Result
> 1 ? 0 ? ?0 ? ?1 ? ?1 ? ?P3,P4
> 2 ? 0 ? ?1 ? ?1 ? ?1 ? ?P2,P3,P4
> 3 ? 1 ? ?0 ? ?0 ? ?0 ? ?P1
> 4 ? 0 ? ?0 ? ?0 ? ?0 ? ?NA
> 5 ? 1 ? ?1 ? ?1 ? ?1 ? ?P1,P2,P3,P4
>
> I'm still relatively new to R and tend to think in for loops. I'm sure there
> exists a more concise and elegant solution. Any advice?
>
> Happy holidays,
> -david
>
> ______________________________________________
> 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
Data Munger Guru
What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.