2016-04-28 11 views
0

Windows 8.1ではRStudioでRx64 3.2.5を実行しています。Rのmean()はオブジェクトだと思う。

私はCourseraのRプログラミングコースでRで関数を作成しています。ディレクトリ 'specdata'のすべてのcsvファイルを読み込み、2つの汚染物質(硫酸塩と硝酸塩)の平均値を取ろうとしています。

pollutantmean <- function(directory, pollutant, id=1:332) { 
monitors <- list.files(directory, pattern=".csv") 
monitorset <- as.vector(monitors[id]) 
     lapply(monitorset, function(x){ 
     t<- read.csv(x, header=TRUE) 
     poll <- t[[pollutant]] 
     mean(poll, na.rm) 

})  
} 

私はそれを呼び出す:私は、次のコードを持っている

pollutantmean(specdata, "sulfate") 

私は、このエラーメッセージが出ます:

Error in mean.default(poll, na.rm) : object 'na.rm' not found 

を平均機能がna.rmを考えて、なぜ私が把握することはできませんオプションでなければならないときのオブジェクトです。

私は、コンソールでコードの個々の行を実行しようとしました。私はまた、エラーを探知し、平均()ヘルプのエントリを確認したが、良い説明が見つかりませんでした。

ありがとうございます!

+4

あなたは引数に値を与えませんでした。 'mean(poll、na.rm = TRUE)'を使うべきです。 – Molx

答えて

5

変更:

mean(poll, na.rm) 

:あるいは

mean(poll, na.rm = TRUE) 

又は

mean(poll) # na.rm = FALSE 

、以下で関数のパラメータとしてna.rmをサポートするための機能を変更します

# Adds the na.rm parameter to the function 
pollutantmean <- function(directory, pollutant, id=1:332, na.rm = TRUE) { 
monitors <- list.files(directory, pattern=".csv") 
monitorset <- as.vector(monitors[id]) 

# Write an inline function w/ na.rm parameter. 
mread = function(x, na.rm = TRUE){ 
     t<- read.csv(x, header=TRUE) 
     poll <- t[[pollutant]] 
     mean(poll, na.rm = na.rm) 
} 

# Calculate and return result w/ function 
lapply(monitorset,FUN = mread, na.rm = na.rm)  
}