我的原始数据集有62个变量。对于我想要循环执行函数boxplot.with.outlier.label的变量,请参见
源(“http://www.r-statistics.com/wp-content/uploads/2011/01/boxplot-with-outlier-label-r.txt"”)
但是我已经被困在构建一个允许我构建循环的函数上了。以下是一些模拟数据(当然不会显示异常值,但据我所知,这不是问题的一部分--证明我错了!)
x <- rnorm(1000)
y <- rnorm(1000)
z <- sample(letters, 1000)
df <- as.data.frame(cbind(x,y,z))
df$x<- as.numeric(df$x)
df$y<- as.numeric(df$y)
df$z<- as.character(df$z)这可以很好地工作:
boxplot.with.outlier.label(df$x, df$z)而这并不是:
boxplotlabel <- function (data, var, name) {
datvar <- data[["var"]]
namevar <- data[["name"]]
boxplot.with.outlier.label(datvar, namevar)
}
boxplotlabel(df, x, z)
Error in plot.window(xlim = xlim, ylim = ylim, log = log, yaxs = pars$yaxs) :need finite 'ylim' values
In addition: Warning messages:
1: In is.na(x) : is.na() applied to non-(list or vector) of type 'NULL'
2: In is.na(x) : is.na() applied to non-(list or vector) of type 'NULL'
3: In is.na(x) : is.na() applied to non-(list or vector) of type 'NULL'
4: In min(x) : no non-missing arguments to min; returning Inf
5: In max(x) : no non-missing arguments to max; returning -Inf我哪里错了?或者有不同的方法来实现我想要的boxplot.with.outlier.label函数循环
感谢大家的帮助!Gerit
发布于 2012-11-16 23:26:46
问题出在引文中。var和name是变量。但是,当您调用data[["var"]] (带引号)时,您使用的不是变量var,而是一个字符串,该字符串的值是字符"var“。
如果你去掉引号,你就成功了一半。Var本身应该有一个字符串值。因此,请确保向它传递列的名称,而不是列本身。
例如:
# If you want to get this:
df$x
df[["x"]] # right
df[[x]] # wrong因此,如果我们为x使用一个变量
# Wrong
var <- x
df[[var]]
# Right
var <- "x"
df[[var]]发布于 2012-11-16 23:36:59
您正在尝试访问不存在的列。这会产生错误。df的所有列都没有命名为var或name。
有两种可能的解决方案
boxplotlabel <- function (data,var,name) { datvar <- data[var] namevar <- data[name] boxplot.with.outlier.label(datvar,namevar) } boxplotlabel(df,"x",“z”)
boxplotlabel <-函数(数据,变量,名称){数据变量<-数据[离开(替换( var ))]名称<-数据[离开(替换(名称))]boxplot.with.outlier.label(数据,名称)}盒子绘图标签(df,x,z)
发布于 2012-11-17 03:41:13
这是函数加循环的最后一组。只是为了得到一个完整的答案,以防另一个新手遇到这个问题。你“只是”需要创建异常值。
#fct.
boxplotlabel <- function (data, var, name) {
datvar <- data[[var]]
namevar <- data[[name]]
boxplot.with.outlier.label(datvar, namevar)
}
#single output:
boxplotlabel(df, "x", "z")
#loop:
col <- names(df[,c(1:2)])
for (i in seq_along(col)){
boxplotlabel(df, col[i], "z")
}https://stackoverflow.com/questions/13419181
复制相似问题