我是 R 新用戶,我的第一份作業需要使用該軟體。我試圖在網站上尋找與我類似的問題,但沒有找到。如果我的問題是多余的,我深表歉意。
我遇到的問題是我需要在每一列中編輯例外值。一個可重現的例子如下:
data_X <- matrix(data = rep(1,100), nrow = 10, ncol = 10)
for (i in 1:nrow(data_x)) {
for (j in 1:ncol(data_x)) {
if (is.na(data_x[i,j])) {
data_x[i,j] <- NA
} else if (data_x[i,j]>(quantile(data_x[[j]], 0.75, na.rm=T) 1.5*(quantile(data_x[[j]], 0.75,na.rm=T)-quantile(data_x[[j]], 0.25,na.rm=T)))) {
data_x[i,j]=(quantile(data_x[[j]], 0.5, na.rm=T))
} else if (data_x[i,j]<(quantile(data_x[[j]], 0.25, na.rm=T)-1.5*(quantile(data_x[[j]], 0.75, na.rm=T)-quantile(data_x[[j]], 0.25, na.rm=T)))) {
data_x[i,j]=(quantile(data_x[[j]], 0.5, na.rm=T))
} else {
data_x[i,j]=data_x[i,j]
}
}
}
實際上,矩陣的維度要大得多,回圈遍歷代碼大約需要 4 分鐘。這對我的目的來說太長了,我想知道是否有更優雅的方式。
我做了一些研究,顯然 apply() 不會提高速度......
編輯:
規則:
高于 75% 分位數 1.5 * 四分位差的資料點;
和
低于 25% 分位數的資料點 - 1.5 * 分位數差;
轉換為中位數。
uj5u.com熱心網友回復:
1.我們創建了一個規則函式,我們在其中使用了向量化的ifelse.
rule_function <- function(x) {
q25 <- quantile(x, 0.25, na.rm = TRUE)
q75 <- quantile(x, 0.75, na.rm = TRUE)
iqr <- q75 - q25
lower <- q25 - 1.5 * iqr
upper <- q75 1.5 * iqr
result <- ifelse(x < lower | x > upper, median(x, na.rm = TRUE), x)
return(result)
}
2.然后我們將函式應用于矩陣的每一列:
apply(data_X, 2, rule_function)
示例資料實際上不允許測驗,所以我不能 100% 確定這是否對您有幫助。但是,對于 10000 x 10000 矩陣,這僅需要幾秒鐘(是否好取決于您的實際用例;)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315508.html
上一篇:如何洗掉嵌套陣列的專案?[復制]
