R类型检查

R Type Checking

我还有一个 R 问题。我正在尝试进行一些类型检查,但无法确切地弄清楚我做错了什么。

我正在尝试为 y 的每个级别创建直方图。因此,例如,我想创建鸢尾花数据种类及其萼片宽度等的叠加直方图

这是我目前的情况:

    #if x isn't numeric
    if(!is.numeric(x)){
    #if y isn't a factor
    }else if(!is.factor(y)){
    #if the length of x isn't equal to y
    }else if(nChar(x) != nChar(y)){
    #error message
    stop('x is not numeric/y is not a factor/both x and y are the same                  length')
}
#otherwise create histogram
#testing with iris data set
hist(y, main = "Iris Species", xlab = "Sepal Width", col = "orange", border   ="blue")

我通常使用stopifnot(),所以你先检查最简单的条件,然后再进行更复杂的;如果第一个无效,您不想一次测试所有这些:

stopifnot(is.numeric(x))
stopifnot(is.factor(y))
stopifnot(length(x) == length(y))

或者,一次完成所有这些:

if(!(is.numeric(x) && is.factor(y) && length(x)==length(y))){
    stop("your error message")
}

现在我不清楚你为什么要在这里测试 y,因为 hist() 没有 'y' 参数。也许您正计划为 y 的每个级别分别绘制 x 的直方图?

如果是这样,您应该能够适应以下内容:

x <- iris$Sepal.Width
y <- iris$Species
l1 <- length(levels(y))
## temporarily change plotting parameters
op <- par(mfrow = c(1, l1))
for (i in 1:l1){
    hist(x[y == levels(y)[i]],
         main=paste0("Iris Species: ", levels(y)[i]),
         xlab = "Sepal Width",
         col="orange",
         border="blue")
}
par(op)

给予:

我不知道 R 中有 nChar 函数; length() 通常用于此。

这是重叠的方法。请注意,for 循环通常比 apply 更易于阅读,并且速度损失可能相对较小。

for (i in 1:l1){
    hist(x[y == levels(y)[i]],
         ## main=paste0("Iris Species: ", levels(y)[i]),
         main="Iris Species: ",
         xlab = "Sepal Width",
         col=i+1,
         add=!(i==1))
}
legend(x=4, y=25, legend=levels(y), fill=1+(1:l1))

给予: