2

I have have a data frame containing 30 columns in R that contain binary data. Every row contains exactly one 1. In other words the binary values are mutually exclusive. For all the thirty columns no two columns can contain 1 in the same row. Here is an illustration of what I mean.

1  0  0
0  1  0 
0  0  1
1  0  0
0  0  1

Now obviously it is computationally enormously expensive to have this information distributed over thirty columns. What I want to do is merge all those 30 columns into one column that contains 30 different factor variables. For example the new column contains 2s in every row where the second column had 1s, 3s in every row where the third column had 1, etc. It is important that the original order is preserved and the positions do not get messed up as they act as index for other columns. So the above 3 columns would become this:

1
2
3
1
3

How can I achieve this in R?

Many thanks

1
  • 6
    you can use max.col(df) Commented Apr 4, 2017 at 12:00

2 Answers 2

4

We can use max.col to find the index of the first value of the dataset

max.col(df1)
#[1] 1 2 3 1 3

Or with pmax

do.call(pmax, col(df1)*df1)
#[1] 1 2 3 1 3

data

df1  <- structure(list(v1 = c(1L, 0L, 0L, 1L, 0L), v2 = c(0L, 1L, 0L, 
0L, 0L), v3 = c(0L, 0L, 1L, 0L, 1L)), .Names = c("v1", "v2", 
"v3"), class = "data.frame", row.names = c(NA, -5L))
Sign up to request clarification or add additional context in comments.

2 Comments

The ties.method specification is unnecessary since there can only be a single 1 per row
@docendodiscimus Thanks, I came to know that you posted the comments first, but I was trying it for many times and I had to wait 60 secs until I can post one :-)
0

Thanks everyone. I also figured out a solution. If my data frame of 30 binary rows and 500 000 rows is called df, I just create a vector of 30 factors and loop through the factors:

factors = c(1:30)
newcol = rep(0, 500000)

for(f in factors){
    colvalues=df[,f]
    newcol[which(colvalues==1)]=f
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.