2017-07-28 32 views
0

我是編程的新手,我試圖在R中編寫一個函數來計算指定的監視器列表中的污染物(硝酸鹽或硫酸鹽)的平均值每個監視器在文件夾「specdata」中都有自己的.csv文件)。我已經構建了以下功能:R:警告:當我嘗試使用我的功能時得到NA

pollutantmean <- function(directory="specdata", pollutant="sulfate", id=1:332) 
{ 
    files_f<-list.files(directory,full.names=TRUE) 
    d <- data.frame() 

    for(i in 1:332){ 
     d <- rbind(d,read.csv(files_f[i])) 
    } 
    if(pollutant=="sulfate"){ 
     mean(d$Sulfate[which(d$ID==id)], na.rm=TRUE) 
    } 
    else{ 
     mean(d$Nitrate[which(d$ID==id)], na.rm=TRUE) 
    } 
} 

然後我試圖與測試功能: pollutantmean(directory="specdata",pollutant="sulfate", id=1:10)

然後我得到以下錯誤:

[1] NA Warning messages: 
1: In d$ID == id : 
longer object length is not a multiple of shorter object length 
2: In mean.default(d$Sulfate[which(d$ID == id)], na.rm = TRUE) : 
argument is not numeric or logical: returning NA 

這是什麼意思?我已經多次查看了代碼,但無法確定問題所在。

謝謝。

+1

(1)你的代碼是通過引用'files_f [I]'「的範圍之內達到了」,這個範圍違規,應避免; (2)你在'id'和'for'循環中都有'1:332'硬編碼,這是故意的嗎? (3)你的問題是因爲你正在比較兩個不同長度的向量,都大於1.你建議結果應該在'1:4 == 1:3'中? (可以清楚地說'1:4 == 1'和'1 == 1:3',但不是雙方都是向量。) – r2evans

+4

(4)[This Coursera topic has been asked to death](https:// stackoverflow.com/search?q=%5Br%5D+pollutantmean) –

+3

富有...你打我到#4你在作業崗位作弊! – sconfluentus

回答

0

在這裏,我認爲我已經在評論中實施了建議,縮短了代碼,甚至推廣了這個功能,以防您想調查其他污染物(只要確保將它們拼寫成與csv相同,包括大寫):

pollutantmean <- function(directory="specdata", 
           pollutant="Sulfate", 
           id=1:332){ 
     files_f <- list.files(directory,full.names=TRUE) 
     d <- do.call(rbind, lapply(files_f, read.csv, stringsAsFactors=FALSE)) 
     mean(d[[pollutant]][which(d$ID %in% id)], na.rm=TRUE) 
    } 

希望這樣的作品,好運與污染物監測

+1

可以通過用'd < - do替換'd < - data.frame()/ for'來進一步簡化代碼。 .call(rbind,lapply(files_f,read.csv))'。 –

+0

謝謝你的幫助。我嘗試了你的代碼,得到[1] NA和錯誤「Warning message: In mean.default(d [[pollutant]] [which(d $ ID%in%id)],na.rm = TRUE): 參數不是數字或邏輯:返回NA「 - 我不明白爲什麼參數不被認爲是數字。有什麼想法嗎?這是否是d $ ID或ID的問題? @RuiBarradas當我推薦你的代碼時,我也會得到相同的錯誤信息。 – Jab

+0

@Jab:這可能是'd $ ID'的問題,它可能是'factor'類。但據我所見,我的代碼與AlexP相當。一種說法是在「mean(...)'指令之前包含一個'print(class(d $ ID))'語句。 –

相關問題