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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With