Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in ncol(xj) : object 'xj' not found when using R matplot()

Tags:

r

Using matplot, I'm trying to plot the 2nd, 3rd and 4th columns of airquality data.frame after dividing these 3 columns by the first column of airquality.

However I'm getting an error

Error in ncol(xj) : object 'xj' not found

Why are we getting this error? The code below will reproduce this problem.

attach(airquality)
airquality[2:4] <- apply(airquality[2:4], 2, function(x) x /airquality[1]) 
matplot(x= airquality[,1], y= as.matrix(airquality[-1]))
like image 465
Nyxynyx Avatar asked Oct 31 '15 18:10

Nyxynyx


1 Answers

You have managed to mangle your data in an interesting way. Starting with airquality before you mess with it. (And please don't attach() - it's unnecessary and sometimes dangerous/confusing.)

str(airquality)
'data.frame':   153 obs. of  6 variables:
 $ Ozone  : int  41 36 12 18 NA 28 23 19 8 NA ...
 $ Solar.R: int  190 118 149 313 NA NA 299 99 19 194 ...
 $ Wind   : num  7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
 $ Temp   : int  67 72 74 62 56 66 65 59 61 69 ...
 $ Month  : int  5 5 5 5 5 5 5 5 5 5 ...
 $ Day    : int  1 2 3 4 5 6 7 8 9 10 ...

After you do

airquality[2:4] <- apply(airquality[2:4], 2, 
                          function(x) x /airquality[1]) 

you get

'data.frame':   153 obs. of  6 variables:
 $ Ozone  : int  41 36 12 18 NA 28 23 19 8 NA ...
 $ Solar.R:'data.frame':    153 obs. of  1 variable:
  ..$ Ozone: num  4.63 3.28 12.42 17.39 NA ...
 $ Wind   :'data.frame':    153 obs. of  1 variable:
  ..$ Ozone: num  0.18 0.222 1.05 0.639 NA ...
 $ Temp   :'data.frame':    153 obs. of  1 variable:
  ..$ Ozone: num  1.63 2 6.17 3.44 NA ...
 $ Month  : int  5 5 5 5 5 5 5 5 5 5 ...
 $ Day    : int  1 2 3 4 5 6 7 8 9 10 ...

or

sapply(airquality,class)
##        Ozone      Solar.R         Wind         Temp        Month          Day 
##     "integer" "data.frame" "data.frame" "data.frame"    "integer"    "integer"

that is, you have data frames embedded within your data frame!

rm(airquality)  ## clean up

Now change one character and divide by the column airquality[,1] rather than airquality[1] (divide by a vector, not a list of length one ...)

airquality[,2:4] <- apply(airquality[,2:4], 2, 
                         function(x) x/airquality[,1])
matplot(x= airquality[,1], y= as.matrix(airquality[,-1]))

In general it's safer to use [, ...] indexing rather than [] indexing to refer to columns of a data frame unless you really know what you're doing ...

like image 50
Ben Bolker Avatar answered Sep 30 '22 19:09

Ben Bolker