Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearrange dataframe - R

Tags:

dataframe

r

melt

I have a dataframe that looks like this:

       a        b       c         d
ab    0        0        1         0
cd   -0.415    1.415    0         0
ef    0        0        0.0811    0.918

Is there an easy way to transform this table into:

       a        b       c         d
ab    0        0        1         0
cd   -0.415    0        0         0
cd    0    1.415        0         0
ef    0        0        0.0811    0
ef    0        0        0         0.918

If there are two or more numbers in the original table I want to transform it into corresponding numbers of rows. I haven't got a clue how to do it so any help would be appreciated

like image 913
rainer Avatar asked Dec 27 '22 09:12

rainer


1 Answers

Borrowing some from @AnandaMahto and melting per your request. Please consider: any unique combination you wish to examine goes on the left hand side~ values for the variable go on the right. In this case variable names became values.

library(reshape2)
mydf <- structure(list(a = c(0, -0.415, 0), b = c(0, 1.415, 0), 
                       c = c(1, 0, 0.0811), d = c(0, 0, 0.918)), 
                  .Names = c("a", "b", "c", "d"), 
                  class = "data.frame", row.names = c("ab", "cd", "ef"))
mydf$rows<- rownames(mydf)
m1<- melt(mydf, id="rows", measured= names(mydf))
m2<- dcast(m1, rows+value~..., fill=0)
m2<- m2[m2$value!=0, ]
m2$value <- NULL    

#rows      a     b      c     d
#2   ab  0.000 0.000 1.0000 0.000
#3   cd -0.415 0.000 0.0000 0.000
#5   cd  0.000 1.415 0.0000 0.000
#7   ef  0.000 0.000 0.0811 0.000
#8   ef  0.000 0.000 0.0000 0.918
like image 130
Jack Ryan Avatar answered Jan 07 '23 08:01

Jack Ryan