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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With