Q:

Reshape data frame in R to wide format

I am trying to convert a long format data frame to wide format using dcast of the reshape2 package. My data frame looks something similar to the data frame below
X = c(3,2,3,3,2,3,3,2,3)
Y = c(-3, -1, -3, -3, -1, -3, -3, -1, -3)
DATA = c(100, 200, 300, 400, 100, 500, 600, 200, 300)
measurement = c("A", "A", "A", "B", "B", "B", "C", "C", "C")
DF <- data.frame(X, Y, DATA, measurement)
wideDF <- dcast(DF, X + Y ~ measurement, fun.aggregate = mean, value.var="DATA", drop = TRUE)

The dcast function works totally fine, but sometimes I have a huge list of column names that I don't want to hard code all the column names (in the above code like X + Y), I would like to pass the column names as a vector or however it makes my code simple. Can I achieve this using the dcast function or is there any function other than dcast to do so? 

A:

You can create the formula as a string, and then use as.formula()
In lhs I'm grabbing all the column names that aren't DATA or measurement by using setdiff().
library(reshape2)
lhs <- paste0(setdiff(names(DF), c("DATA", "measurement")), collapse = "+")

dcast(DF, as.formula(paste0(lhs, "~ measurement")), fun.aggregate = mean, value.var = "DATA", drop = TRUE)
#   X  Y   A   B   C
# 1 2 -1 200 100 200
# 2 3 -3 200 450 450

