Santosh Santosh - 3 years ago 124
R Question

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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download