Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reformat data from long to wide

Tags:

r

tidyr

reshape2

How can I reformat this data to a wide format?

species val    price
setosa  5.1     3
setosa  4.9     3
setosa  4.7     3
setosa  4.6     2

Desired output:

species val1 val2 val3 val4 price1 price2 price3 price4
setosa  5.1  4.9  4.7  4.6    3       3      3      2

I have tried spread from tidyr but without success.

like image 485
lizzie Avatar asked Dec 10 '22 17:12

lizzie


1 Answers

data.table v 1.9.6+ allows you to pass more than one value.vars, so you can simply do

library(data.table)
dcast(setDT(df), species ~ val + price, value.var = c("val", "price"))
#    species val.1_4.6_2 val.1_4.7_3 val.1_4.9_3 val.1_5.1_3 price.1_4.6_2 price.1_4.7_3 price.1_4.9_3 price.1_5.1_3
# 1:  setosa         4.6         4.7         4.9         5.1             2             3             3             3
like image 139
David Arenburg Avatar answered Dec 29 '22 11:12

David Arenburg