How to calculate mean of a list of each csv data frames

Viewed 58

I have more than 30 csv files with the same amount of columns and rows and the same name header. I am trying to calculate the mean on one of the columns for each file and putting them into a new file with each of my csv file name and calculated mean. This is how my data looks: data

I have used list files:

estaciones <- list.files(path = "D:/A/",
                            recursive = T, pattern = "PRCPTOT.csv", full.names = T)

And then I read the csv's using:

estaciones = lapply(estaciones, read.csv)

I also need to change -99-9 values to NA, but the next code line does not seem to be working fine:

lapply(estaciones, function(prcptot) {prcptot[prcptot ==-99.9] <- NA; return(prcptot)})

When I see my data it seems to have made the replacement, but when I try to calculate the mean with the following code, I get NA values for each of my data frames.

apply(estaciones, mean)

How can replace values correctly for all of my files, calculate mean for each data frame and creating a new file with the calculated means for each csv file and respective names? Thank you

2 Answers

try to do it this way

l <- split(mtcars, mtcars$vs)

l_split <- lapply(l, function(x) {x$cyl[x$cyl == 6] <- NA; x})

sapply(l_split, function(x) apply(x, 2, mean, na.rm = T))
#>                0          1
#> mpg   16.6166667  24.557143
#> cyl    7.7333333   4.000000
#> disp 307.1500000 132.457143
#> hp   189.7222222  91.357143
#> drat   3.3922222   3.859286
#> wt     3.6885556   2.611286
#> qsec  16.6938889  19.333571
#> vs     0.0000000   1.000000
#> am     0.3333333   0.500000
#> gear   3.5555556   3.857143
#> carb   3.6111111   1.785714

Created on 2021-07-13 by the reprex package (v2.0.0)

You can perform the calculations in the same lapply loop -

res <- do.call(rbind, lapply(estaciones, function(x) {
  #Read the csv
  prcptot <- read.csv(x)
  #Change -99.9 to NA
  prcptot[prcptot ==-99.9] <- NA
  #Find column-wise mean of all the columns
  colMeans(prcptot, na.rm = TRUE)
}))

do.call(rbind, ...) would combine output of all the files in one dataframe call res.

Related