Santosh M.
Santosh M.

Reputation: 2454

Creating a matrix from data frame

I have a data frame df1 with 5 columns c1, c2, c3, c4, and c5:

df1 <- data.frame(c1 = c(1, 0, 1), c2 = c(0, 0, 1), c3 = c(2, 1, 0), c4 = c(1, 4, 3), c5 = c(1, 0, 0)) 

  #df1
  c1 c2 c3  c4  c5
  1  0  2   1   1
  0  0  1   4   0
  1  1  0   3   0 

My desired output is:

  1  3  3   4  5
  3  4  4   4  4
  1  2  4   4  4

Basically, I am creating matrix based on the column number and its value (value is always less than or equal to 5). For example, 2nd row in df1 has 1 and 4 belongs to column c3 and c4. So, 2nd row in desired matrix would be 3 4 4 4 4.

I have tried by myself. My code involves several nested control flows and not working well for a large data frame.

Upvotes: 1

Views: 88

Answers (2)

akrun
akrun

Reputation: 887028

Here is a slightly different option

t(apply(df1, 1, FUN = function(x) rep(which(x!=0), x[x!=0])))
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    3    3    4    5
#[2,]    3    4    4    4    4
#[3,]    1    2    4    4    4

Upvotes: 1

Pierre L
Pierre L

Reputation: 28441

A little apply magic:

t(apply(df, 1, function(x) rep(row(as.matrix(x)), x)))
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    3    3    4    5
#[2,]    3    4    4    4    4
#[3,]    1    2    4    4    4

Upvotes: 2

Related Questions