Cast {reshape}: using variables instead of column names

Say I have a data frame:

data <- data.frame(id=c(1,2,2,2), 
                   code=c("A","B","A","B"), 
                   area=c(23.1,56.0,45.8,78.5))

and this line of code works fine:

df<-cast(data,id~code,fun.aggregate=sum)

Then I create the following variables:

ID <- "id"

CODE <- "code"

and use the variables as arguments in the translation function:

df <- cast(data, ID~CODE, fun.aggregate=sum)

Then I get the following error:

Error: Casting formula contains variables not found in molten data: ID, CODE

How to use variables instead of column names with translation function?

+4
source share
2 answers

You need to build a formula:

cast(data, as.formula(paste(ID, CODE, sep="~")), fun.aggregate=sum)

However, the package conversion has been replaced by the reshape2 package (look at its function dcastand see @Ananda Mahto's comment). A function reshapein the R database may also interest you.

+4
source

You can also use do.call ():

do.call("cast", args = list(data = data, formula = paste(ID, '~', Code), fun.aggregate = "sum"))

( ) .

0

All Articles