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

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

However, I get 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])) 
+6
source share
1 answer

You managed to remove your data in an interesting way. Starting with airquality , before you start working with it. (And please do not attach() - this is 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 doing

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

You are getting

 '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 in your data frame!

 rm(airquality) ## clean up 

Now change one character and divide it into the column airquality[,1] , not airquality[1] (divide by 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 is safer to use indexing [, ...] rather than [] to refer to columns of a data frame if you really don't know what you are doing ...

+7
source

All Articles