Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshape column values to column names

Tags:

r

reshape

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.

like image 838
user3310782 Avatar asked Feb 09 '23 18:02

user3310782


2 Answers

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
like image 191
akrun Avatar answered Feb 12 '23 07:02

akrun


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
like image 21
Veerendra Gadekar Avatar answered Feb 12 '23 07:02

Veerendra Gadekar