Daniel Nordlund
2009-Dec-18 20:48 UTC
[R] how to combine multiple indicator variables in a single factor
Say I have a dataframe like this: df <- data.frame(cbind(c(1,0,0,1),c(0,1,0,0),c(0,0,1,0))) names(df) <- c('a','b','c') I would like to create a factor in a new column, where the factor values are taken from the column names, like this:> df2a b c f 1 1 0 0 a 2 0 1 0 b 3 0 0 1 c 4 1 0 0 a How would I do this? Thanks, Dan Daniel Nordlund Bothell, WA USA
ehud cohen
2009-Dec-18 21:04 UTC
[R] how to combine multiple indicator variables in a single factor
you can try: df$f<-names(df)[apply(df,1,function(x) which(x==1))] Ehud On Fri, Dec 18, 2009 at 10:48 PM, Daniel Nordlund <djnordlund at verizon.net> wrote:> Say I have a dataframe like this: > > df <- data.frame(cbind(c(1,0,0,1),c(0,1,0,0),c(0,0,1,0))) > > names(df) <- c('a','b','c') > > I would like to create a factor in a new column, where the factor values are taken from the column names, like this: > >> df2 > ?a b c f > 1 1 0 0 a > 2 0 1 0 b > 3 0 0 1 c > 4 1 0 0 a > > How would I do this? ?Thanks, > > Dan > > Daniel Nordlund > Bothell, WA USA > > ______________________________________________ > 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. >
William Dunlap
2009-Dec-18 21:57 UTC
[R] how to combine multiple indicator variables in a single factor
> -----Original Message----- > From: r-help-bounces at r-project.org > [mailto:r-help-bounces at r-project.org] On Behalf Of Daniel Nordlund > Sent: Friday, December 18, 2009 12:49 PM > To: r-help at r-project.org > Subject: [R] how to combine multiple indicator variables in a > single factor > > Say I have a dataframe like this: > > df <- data.frame(cbind(c(1,0,0,1),c(0,1,0,0),c(0,0,1,0))) > > names(df) <- c('a','b','c') > > I would like to create a factor in a new column, where the > factor values are taken from the column names, like this: > > > df2 > a b c f > 1 1 0 0 a > 2 0 1 0 b > 3 0 0 1 c > 4 1 0 0 a > > How would I do this? Thanks,One possibility is > df$f <- factor(df$a + df$b*2 + df$c*3, labels=names(df)[1:3]) > df a b c f 1 1 0 0 a 2 0 1 0 b 3 0 0 1 c 4 1 0 0 a Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com> > Dan > > Daniel Nordlund > Bothell, WA USA > > ______________________________________________ > 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. >