Calculate the Mean of One Column from Several CSV Files

Calculate the mean of one column from several CSV files

You do not need more functions. The solution can be simpler from my understanding in 6 lines:

pollutantmean <- function(directory, pollutant, id = 1:10) {
filenames <- sprintf("%03d.csv", id)
filenames <- paste(directory, filenames, sep="/")
ldf <- lapply(filenames, read.csv)
df=ldply(ldf)
# df is your list of data.frames
mean(df[, pollutant], na.rm = TRUE)
}

How to find mean of values over multiple csv files in R

There are a few ways to load files into R, but probably the easiest is using the list.files function. Your code would look something like this:

setwd("")  # set to your directory
files <- list.files() #load the file names into the workspace
for(i in sequence(length(files))){
yourData <- read.scv(files[i])
yourMeans <- apply(yourData, 1, mean)
#save your means in some meaningful way from each csv.
}

calculating Average of each cell across multiple csv

import pandas as pd
df=pd.read_csv("a1.csv")
for i in range(2,21):
filename="a"+str(i)+".csv"
df+=pd.read_csv(filename)
df=df/20

This should do the trick..

Mean values from multiple csv to data frame

I'd also suggest to use (l)apply... Here's my take:

getMeans <- function(fpath,runfct,
target_cols = c(2),
sep=",",
dec=".",
header = T,
min_obs_threshold = 3){

f <- list.files(fpath)
fcsv <- f[grepl("\.csv",f)]

fcsv <- paste0(fpath,fcsv)

csv_list <- lapply(fcsv,read.table,sep = sep,
dec = dec, header = header)

csv_rows <- sapply(csv_list,nrow)

rel_csv_list <- csv_list[!(csv_rows < min_obs_threshold)]

lapply(rel_csv_list,function(x) colMeans(x[,target_cols]))

}

Also with that kind of error message, the debugger might be very helpful.
Just run debug(moist.each.mean) and execute the function stepwise.



Related Topics



Leave a reply



Submit