Rdidds Rdidds - 1 month ago 14
R Question

CAST ERROR IN R Error in `[.data.frame`(data, , variables, drop = FALSE) : undefined columns selected

I am getting this error in R when casting data using package "Reshape":

"Error in `[.data.frame`(data, , variables, drop = FALSE) :
undefined columns selected"


Waterquality Data look like this:

year turbid.ave.mo month2
16 2002 926.66667 JUNE
23 2002 493.66667 JULY
29 2002 107.10000 AUG
37 2002 295.80000 SEPT
46 2002 528.28000 OCT
53 2002 266.20000 NOV
56 2002 73.80000 DEC
1 2003 115.00000 JAN


I want to cast so that month is column header (one row per year with JAN to DEC as column headers.

Code I tried:

casted = cast(Waterquality [ ,c(1:3)], year + turbid.ave.mo ~ month2, mean, fill =0, value = "turbid.ave.mo")


Error: Error in
[.data.frame
(data, , variables, drop = FALSE) :
undefined columns selected

Anybody tell me what I am doing wrong? Thanks in advance!!

Answer

Here's a much cleaner tidyr solution:

library(tidyr)

spread(Waterquality, month2, turbid.ave.mo, fill = 0)
# year        Apr      Aug       Feb        Jan         Jul      Jun        Mar       May
# 1 2002 -0.2798722 0.000000 -0.901421 -0.9576323 -0.07627388 0.652116 -0.3758433 0.9795479
# 2 2003  0.0000000 1.047832  0.000000  0.0000000  0.00000000 0.000000  0.0000000 0.0000000