Ash*_*ley -2 r histogram typechecking
我还有另一个 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")
Run Code Online (Sandbox Code Playgroud)
我通常stopifnot()用于此,以便您先检查最简单的条件,然后再进行更复杂的条件;如果第一个无效,您不想一次测试所有这些:
stopifnot(is.numeric(x))
stopifnot(is.factor(y))
stopifnot(length(x) == length(y))
Run Code Online (Sandbox Code Playgroud)
或者,一次性完成所有这些:
if(!(is.numeric(x) && is.factor(y) && length(x)==length(y))){
stop("your error message")
}
Run Code Online (Sandbox Code Playgroud)
现在我不清楚你为什么在y这里测试,因为没有 'y' 参数hist()。也许您打算x为每个级别绘制单独的直方图y?
如果是这样,您应该能够调整以下内容:
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)
Run Code Online (Sandbox Code Playgroud)
给予:

我不知道nCharR 中有一个函数;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))
Run Code Online (Sandbox Code Playgroud)
给予:
