luciano
luciano

Reputation: 13802

function that outputs R code

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

Upvotes: 0

Views: 116

Answers (1)

eddi
eddi

Reputation: 49448

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")

Upvotes: 3

Related Questions