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.
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
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