Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast {reshape}: using variables instead of the columns' name

Say I have a dataframe:

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 that's working 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 cast 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 can I use variables instead of the columns' name with the cast function?

like image 316
Hugo Avatar asked Oct 02 '22 08:10

Hugo


1 Answers

You need to construct a formula:

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

However, package reshape has been superseded by package reshape2 (have a look at its function dcast and see @Ananda Mahto's comment). The reshape function in base R might also be of interest to you.

like image 137
Roland Avatar answered Oct 13 '22 12:10

Roland