r - creating a function which extracts a user specified column from a set of files -
i have set of csv files. of them have same structure. want create function extracts particular column files. finds mean of values in column , store in vector. column name should passed user.
i have coded following program. somehow can not identify "pollutant" contains name of column.
pollutantmean<-function(pollutant) { file_names<-dir("c:/users/keval/desktop/project r/r_courseera_programming_exercise/specdata",pattern= glob2rx("*.csv")) for(file_name in file_names) { file_reader<-read.csv(file_name) pollutant_data<-file_reader$pollutant } pollutant_data pollutant }`enter code here`
use string, e.g., call function with
pollutantmean(pollutant = "mercury")
and use [
(which accepts strings) instead of $
, doesn't:
# replace line pollutant_data <- file_reader$pollutant # this: pollutant_data <- file_reader[, pollutant]
this won't error out, still need take mean , store it. i'm pretty sure want list.files
, not dir
.
pollutantmean<-function(pollutant) { file_names <- list.files("c:/users/keval/desktop/projectr/r_courseera_programming_exercise/specdata", pattern= glob2rx("*.csv")) # initialize mean vector @ correct length my_means = numeric(length(file_names) # make loop indexed number for(i in seq_along(file_names)) { file_reader <- read.csv(file_names[i]) pollutant_data <- file_reader[, pollutant] # using number index my_means[i] = mean(pollutant_data) } return(my_means) }
Comments
Post a Comment