Here is one approach, but you will need to keep track of some cosmetic changes to correct line names.
Your data in reproducible form:
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"))
Replace zeros with NA s:
mydf[mydf == 0] <- NA
stack your data.frame to make it a "long" data.frame :
mydf1 <- data.frame(Rows = rownames(mydf), stack(mydf))
Create unique values ββfor strings ""
mydf1$Rows <- make.unique(as.character(mydf1$Rows))
Now just use xtabs to get the result you are looking for. Wrap it in as.data.frame.matrix if you want data.frame , and clear the row names if you need to.
as.data.frame.matrix(xtabs(values ~ Rows + ind, mydf1)) # abcd # ab.2 0.000 0.000 1.0000 0.000 # cd -0.415 0.000 0.0000 0.000 # cd.1 0.000 1.415 0.0000 0.000 # ef.2 0.000 0.000 0.0811 0.000 # ef.3 0.000 0.000 0.0000 0.918