【发布时间】:2020-03-23 12:32:30
【问题描述】:
我目前正在尝试根据所选变量的子集排除异常值,以执行敏感性分析。我已经调整了此处可用的功能:calculating the outliers in R),但到目前为止一直不成功(我仍然是新手 R 用户)。如果您有任何建议,请告诉我!
df <- data.frame(ID = c(1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011),
measure1 = rnorm(11, mean = 8, sd = 4),
measure2 = rnorm(11, mean = 40, sd = 5),
measure3 = rnorm(11, mean = 20, sd = 2),
measure4 = rnorm(11, mean = 9, sd = 3))
vars_of_interest <- c("measure1", "measure3", "measure4")
# define a function to remove outliers
FindOutliers <- function(data) {
lowerq = quantile(data)[2]
upperq = quantile(data)[4]
iqr = upperq - lowerq #Or use IQR(data)
# we identify extreme outliers
extreme.threshold.upper = (iqr * 3) + upperq
extreme.threshold.lower = lowerq - (iqr * 3)
result <- which(data > extreme.threshold.upper | data < extreme.threshold.lower)
}
# use the function to identify outliers
temp <- FindOutliers(df[vars_of_interest])
# remove the outliers
testData <- testData[-temp]
# show the data with the outliers removed
testData
【问题讨论】:
-
错误发生在
df[cogvars],在你有机会运行FindOutliers之前。变量cogvars中有什么?只要您将向量传递给FindOutliers,您的代码就应该可以工作。如果您想要代码审查,请在codereview 上发帖(并可选择使用@asac 联系我)! -
确保使用
df$col或df[["col"]]从 data.frame 中提取列作为向量。使用df["col"]选择列,但在需要向量时返回 data.frame。 -
而
quantile需要一个向量输入——看起来你正试图向它发送一个数据帧?如果df[cogvars]你实际上是指df[, vars_of_interest]。您将需要apply系列函数之一来遍历您想要的列 -
还有一件事——你想对异常值做什么?将它们设置为失踪?删除包含异常值的列?你想让你的输出看起来像吗?这将有助于了解。
-
感谢您提供的所有有用建议。关于
df[, vars_of_interest],您是正确的@pagmo,我已在原始问题中对此进行了修改。我想将它们设置为缺失并随后排除它们。