使用matplot
,在将这3列除以airquality
的第一列之后,我试图绘制airquality
data.frame的第二,第三和第四列。
但是我遇到一个错误
Error in ncol(xj) : object 'xj' not found
为什么会出现此错误?下面的代码将重现此问题。
attach(airquality)
airquality[2:4] <- apply(airquality[2:4], 2, function(x) x /airquality[1])
matplot(x= airquality[,1], y= as.matrix(airquality[-1]))
最佳答案
您已经设法以一种有趣的方式处理数据。从airquality
开始,然后再弄乱它。 (并且请不要attach()
-这是不必要的,有时是危险的/令人困惑的。)
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 ...
做完之后
airquality[2:4] <- apply(airquality[2:4], 2,
function(x) x /airquality[1])
你得到
'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 ...
或者
sapply(airquality,class)
## Ozone Solar.R Wind Temp Month Day
## "integer" "data.frame" "data.frame" "data.frame" "integer" "integer"
即you have data frames embedded within your data frame!
rm(airquality) ## clean up
现在更改一个字符,然后除以
airquality[,1]
列,而不是airquality[1]
列(除以向量,而不是长度为一的列表...)airquality[,2:4] <- apply(airquality[,2:4], 2,
function(x) x/airquality[,1])
matplot(x= airquality[,1], y= as.matrix(airquality[,-1]))
通常,除非您真的知道自己在做什么,否则使用
[, ...]
索引而不是[]
索引来引用数据帧的列更为安全。关于r - ncol(xj): object 'xj' not found when using R matplot()中的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33455168/