0

I have a dataframe in long format, like this one:

longData <- mtcars[1:5, 1:4]
library(reshape2)
melt(longData)

Using  as id variables
   variable value
1       mpg  21.0
2       mpg  21.0
3       mpg  22.8
4       mpg  21.4
5       mpg  18.7
6       cyl   6.0
7       cyl   6.0
8       cyl   4.0
9       cyl   6.0
10      cyl   8.0
11     disp 160.0
12     disp 160.0
13     disp 108.0
14     disp 258.0
15     disp 360.0
16       hp 110.0
17       hp 110.0
18       hp  93.0
19       hp 110.0
20       hp 175.0

Is it possible to make a function that would spit out the R code that would build the same dataframe in wide format? Note: I do not want to convert longData to wide format, I want to programatically output R code code that would convert the dataframe to wide format, like this:

someFunctionToOutputWideCode()

data.frame(mpg = c(21.0, 21.0, 22.8, 21.4, 18.7),
           cyl = c(6, 6, 4, 6, 8),
           disp = c(160, 160, 108, 258, 360),
           hp = c(110, 110, 93, 110, 175))
2
  • 1
    Why not just wrap the code which would convert the data to wide format inside dput()? May 17, 2013 at 21:15
  • @BrianDiggs why not read the answers first ;)
    – eddi
    May 17, 2013 at 22:10

1 Answer 1

3

I don't think that's what people mean when they talk about long and wide formats, but how about this to achieve what you want?

dput(as.data.frame(t(longData)))
# structure(list(`Mazda RX4` = c(21, 6, 160, 110), `Mazda RX4 Wag` = c(21, 
# 6, 160, 110), `Datsun 710` = c(22.8, 4, 108, 93), `Hornet 4 Drive` = c(21.4, 
# 6, 258, 110), `Hornet Sportabout` = c(18.7, 8, 360, 175)), .Names = c("Mazda RX4", 
# "Mazda RX4 Wag", "Datsun 710", "Hornet 4 Drive", "Hornet Sportabout"
# ), row.names = c("mpg", "cyl", "disp", "hp"), class = "data.frame")

Re OP edit: same idea - convert it to whatever format you like, and then dput it

dput(dcast(melt(longData), 1:5 ~ variable))
# structure(list(`1:5` = 1:5, mpg = c(21, 21, 22.8, 21.4, 18.7), 
#     cyl = c(6, 6, 4, 6, 8), disp = c(160, 160, 108, 258, 360), 
#     hp = c(110, 110, 93, 110, 175)), .Names = c("1:5", "mpg", 
# "cyl", "disp", "hp"), row.names = c(NA, -5L), class = "data.frame")
1
  • Apologies, just realised mtcars was already in wide format. Question amended.
    – luciano
    May 17, 2013 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.