2

I am trying to use dcast(), but I can't figure out why I get this error:

"Error : value.var (mpg) not found in input". Dcast can't seem to find "mpg" which I made a measure.vars in the melt function.

Can you guys help me?

Here is my code:

data("mtcars")
install.packages("reshape")
library(reshape)  
install.packages("reshape2")
library(reshape2)

mdata <- melt(mtcars, id=c("gear","cyl"), measure.vars = c("mpg","hp"))
castData <- dcast(mdata, gear ~ cyl, value.var="mpg")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Willy Mercier
  • 21
  • 1
  • 2
  • Please check the `mdata`. There is no 'mpg' column. You may need to `value.var = "value"` Also, there are duplicates for the grouping. So, create a sequence column i.e. `data.table::dcast(mdata, gear + rowid(gear) ~ cyl, value.var="value")` – akrun Jan 05 '18 at 08:51

2 Answers2

0

if you check the object that you have created mdata with

View(mdata)

you can see that there is no column called mpg.

You can create a column like this:

mdata <- dcast(mdata, gear + rowid(gear) ~ cyl, value.var="value")
Lorenzo Benassi
  • 621
  • 1
  • 8
  • 31
0

I wonder if you are trying to recast the data for the mpg, which as already mentioned by @akrun and @Lorenzo is not a field in mdata. You melted the hp and mpg fields in mtcars to become values in a single field called variable.

Also, your call to dcast is incomplete - you should specify what aggregate function to use. As an example of the use of dcast, I've adapted your dcast statement to show the mpg and hp from the melted variable field in mdata with the mean as the aggregate:

castData <- dcast(mdata, gear + variable ~ cyl, value.var="value", fun.aggregate = mean)
> castData
  gear variable       4      6        8
1    3      mpg  21.500  19.75  15.0500
2    3       hp  97.000 107.50 194.1667
3    4      mpg  26.925  19.75      NaN
4    4       hp  76.000 116.50      NaN
5    5      mpg  28.200  19.70  15.4000
6    5       hp 102.000 175.00 299.5000

As an aside, you don't need to attach the reshape library either - reshape2 suffices.

Stewart Ross
  • 1,034
  • 1
  • 8
  • 10
  • I did what you suggested but It says "can't find cyl" – Willy Mercier Jan 05 '18 at 18:14
  • I am using the exact statement you posted to generate mdata: mdata <- melt(mtcars, id=c("gear","cyl"), measure.vars = c("mpg","hp")) - note that the "cyl" field is in your id list (along with gear). You are clearly executing a slightly different statement that does not have "cyl" in the id list. – Stewart Ross Jan 05 '18 at 18:22