[R] reduce three columns to one with the colnames
Gabor Grothendieck
ggrothendieck at gmail.com
Mon May 13 19:11:30 CEST 2013
On Mon, May 13, 2013 at 11:22 AM, David Studer <studerov at gmail.com> wrote:
> 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...
>
Here is a translation of a few of the solutions I posted to this new setup.
First assume this input:
# input data frame
data <- data.frame(male = c(1, 0, 0, 1),
female = c(0, 0, 1, 0),
transsexual = c(0, 1, 0, 0))
# define which columns participate
cols <- c("male", "female", "transsexual")
The solutions below each use this index vector:
ix <- c(as.matrix(data[cols]) %*% seq_along(cols))
# 1
data$new <- factor(ix, labels = cols)
# 4
data$new <- cols[ix]
More information about the R-help
mailing list