2016-05-27 20 views
0

私は完全なRのnoobです。私はRのトラフのCourseraを習得しようとしています...私は332の異なるcsvファイルの平均を計算する関数を書こうとしています。私は正しい値を得ていますが、出力は間違っています。私は要因の1つの平均値を取得するはずですが、代わりに私は両方の要因のためにそれを取得しています。R:出力関数、出力の要因数が間違っている

#Assign the directory 
pollutantmean <- function (directory, pollutant, id = 1:332) { 
  
    directory <- list.files(path= "/Users/......./specdata") 

    #Create empty vector 
  g <- list() 

    #For loop to run through the files and get info and use rbind to create df 
    for(i in 1:length(directory)) { 

    g[[i]] <- read.csv(directory[i],header=TRUE) 

    } 

    rbg <- do.call(rbind,g) 

    #Subset to get the sulfate/nitrate columns and calcualte the mean 
    pollutant <- subset(rbg,ID %in% id ,select = c("sulfate","nitrate")) 
    colMeans(pollutant,na.rm = TRUE) 
   
} 

pollutantmean("specdata","sulfate",70:72) 

sulfate nitrate 
0.9501894 1.7060474 

これまでのところ、とても良い...の値が正しいです。しかし、問題は、私が汚染物質に "硫酸塩"を渡しているので、私は硫酸塩の意味だけを得なければならないということです。しかし、代わりに私は両方を得ています。何故ですか?私はここで間違って何をしていますか?

おかげで、

+0

(i)関数内のパラメータディレクトリは、最初の行のパラメータを置き換えるため、かなり役に立たない。 (ii)汚染物質パラメータは、同様にあなたの機能において同じ名前の「汚染物質」に置き換えられるので、あなたの機能において同様に無用である。 –

答えて

0

が適切にあなたのコードに見て、あなたはあなたの関数にハードコーディングc("sulfate", "nitrate")を持っています。関数に渡す変数は、そのようにハードコーディングする必要はありません。

次にあなたの関数を変更し

#Assign the directory 
pollutantmean <- function (directory, pollutant, id = 1:332) { 
  
    directory_files <- list.files(path = directory) 

    #Create empty vector 
  g <- list() 

    #For loop to run through the files and get info and use rbind to create df 
    for(i in 1:length(directory_files)) { 

    g[[i]] <- read.csv(directory_files[i],header=TRUE) 

    } 

    rbg <- do.call(rbind,g) 

    #Subset to get the sulfate/nitrate columns and calcualte the mean 
    pollutant_subset <- subset(rbg,ID %in% id ,select = pollutant) 
    colMeans(pollutant_subset,na.rm = TRUE) 
   
} 

pollutantmean("/Users/......./specdata","sulfate",70:72) 

sulfate 
0.9501894 

あなたは今、適切な結果を取得する必要があります。

関連する問題