Reshape column values to column names

554 views Asked by At

I've got a dataset with the following structure:

df <- data.frame(mult=c(1,2,3,4),red=c(1,0.9,0.8,0.7),
result=c('value1','value2','value3','value4'))

that I'd like to display in a 3-D plot (x axis: mult, y axis: red, and the x-y points would be 'result') or multiple 2-D plots. Obviously the real DF has a lot more rows and combinations of mult&red.

Columns mult & red do not have values repeated. What I'd like is to reshape DF to DF1:

-   1      0.9      0.8     0.7
1   value1 
2          value2
3                  value3
4  .....

so essentially:

1) [mult] values stays as it is (column 1)
2) [red] values become the column names.
3) Each cross between 'mult' and 'red' is a value in the new DF

My preference would be to do this with the reshape function, but other packages are fine too.

Thanks in advance, p.

3

There are 3 answers

0
akrun On BEST ANSWER

Try

 library(reshape2)
 df1 <- transform(df, result=as.character(result), 
                  red= factor(red, levels= unique(red)))
 dcast(df1, mult~red, value.var='result', fill='')[-1]
 #        1    0.9    0.8    0.7
 #1 value1                     
 #2        value2              
 #3               value3       
 #4                      value4
0
Veerendra Gadekar On

Here is a way using tidyr

library(tidyr)
out = rev(spread(df[-1], red, result))
out[is.na(out)] = ''

#> out
#       1    0.9    0.8    0.7
#1 value1                     
#2        value2              
#3               value3       
#4                      value4
0
stok On

Using reshape as you requested

df <- data.frame(mult=c(1,2,3,4),red=c(1,0.9,0.8,0.7),
                 result=c('value1','value2','value3','value4'))
df$result = as.character(df$result)
dfWide = reshape(data = df, idvar = "mult", timevar = "red", v.names = "result", direction = "wide")
rownames(dfWide) = dfWide$mult
dfWide$mult = NULL
colnames(dfWide) = gsub(pattern = "result.", replacement = "", colnames(dfWide) )
dfWide[is.na(dfWide)] = ''
dfWide

#        1    0.9    0.8    0.7
# 1 value1                     
# 2        value2              
# 3               value3       
# 4                      value4