Skip to content
Prev 323445 / 398503 Next

reduce three columns to one with the colnames

HI,
May be:
dat1<- read.table(text="
male female transsexuals
0 1 0
1 0 0
0 0 1
0 1 0
1 0 0
1 0 0
0 1 0
",sep="",header=TRUE)

?dat1$sex<-colnames(dat1)[apply(dat1,1,function(x) which(x==1))]
?dat1
#? male female transsexuals????????? sex
#1??? 0????? 1??????????? 0?????? female
#2??? 1????? 0??????????? 0???????? male
#3??? 0????? 0??????????? 1 transsexuals
#4??? 0????? 1??????????? 0?????? female
#5??? 1????? 0??????????? 0???????? male
#6??? 1????? 0??????????? 0???????? male
#7??? 0????? 1??????????? 0?????? female


A.K.



----- Original Message -----
From: David Studer <studerov at gmail.com>
To: Bert Gunter <gunter.berton at gene.com>
Cc: r-help at r-project.org
Sent: Monday, May 13, 2013 11:22 AM
Subject: Re: [R] reduce three columns to one with the colnames

OK, seems like nobody understood my question ;-)

Let's make another example:

I have three variables:
data$male and data$female and data$transsexuals

All the three of them contain the values 0 and 1.

Now I'd like to create another variable data$sex. Now in all cases where
data$female==1 the variable data$sex should be set to 'female', all in all
cases
where data$male==1 the variable data$sex should be set to 'male' and so
on...

Thank you!

David




2013/5/13 Bert Gunter <gunter.berton at gene.com>
??? [[alternative HTML version deleted]]

______________________________________________
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.