2016-03-02 33 views
0

我想編寫一個函數,該函數將輸入data.frame作爲輸入,並返回一個新的data.frame,該函數使用預測包中的tsclean()函數替換異常值。從數據框中刪除異常值的功能

對於例如輸入df(含明顯的異常值):

df <- data.frame(col1 = runif(24, 400, 700), 
       col2 = runif(24, 350, 600), 
       col3 = runif(24, 600, 940), 
       col4 = runif(24, 2000, 2600), 
       col5 = runif(24, 950, 1200)) 

colnames(df) <- c("2to2", "2to6", "17to9", "20to31", "90to90") 
df$`2to2`[[12]]=10000 
df$`17to9`[[20]]=6000 
df$`20to31`[[8]]=12000 

我一直在試圖解決這個如下

clean_ts <- function(df, frequency = 12, start = c(2014, 1), end = c(2015, 12)) { 

    ts <- ts(df, frequency = frequency, start = start, end = end) 
    results <- list() 

    for (i in 1:ncol(ts)) { 
    clean <- as.data.frame(tsclean(ts[,i])) 
    results[[i]] <- as.data.frame(cbind(clean)) 
    } 
    return(results) 
} 

我知道這是不對的。我不想返回一個列表,而是希望我的函數返回一個data.frame,它的尺寸和列名與我的輸入data.frame相同。我只想根據tsclean()函數替換data.frame()的列。因此,從例如我的輸出將有以下形式:

2to2 2to6 17to9 20to31 90to90 
.  .  .  .  . 
.  .  .  .  . 
+1

http://stackoverflow.com/questions/12866189/calculating-the-outliers-in-r 這可能對你也有一定的用處。 想法是你創建一個數據框的功能,通過查找分位數,上下閾值來總結數據框並過濾掉該範圍以外的最終數據集。 – InfiniteFlashChess

回答

2

你的問題是,你想將其分配到列表中時,使每一列的數據幀。這是不必要的。我們還可以通過逐個覆蓋df對象中的列來避免initialize-to-list-and-cbind工作流程。

clean_ts <- function(df, frequency = 12, start = c(2014, 1), end = c(2015, 12)) { 

    ts <- ts(df, frequency = frequency, start = start, end = end) 

    for (i in 1:ncol(ts)) { 
    df[, i] <- tsclean(ts[, i]) 
    } 
    return(df) 
} 

即使是比較清潔,我們可以使用lapply隱藏循環:

clean_ts <- function(df, frequency = 12, start = c(2014, 1), end = c(2015, 12)) { 
    ts <- ts(df, frequency = frequency, start = start, end = end) 
    return(as.data.frame(lapply, ts, tsclean))) 
} 
+0

這正是我所期待的。謝謝! –