[R] Compute RowMeans from mulple files

Jim Lemon drjimlemon at gmail.com
Mon Aug 24 11:20:15 CEST 2015


Hi Peter,
I think your problem is that your calculations occur after the end of
the loop. What you probably want is something like this:

yr_means<-mam_means<-jf_means<-
 jja_means<-ond_means<-rep(NA,length(prec_files))
for (i in 1:length(prec_files)) {
 prec_data<-read.delim(prec_files[i], sep="\t",header = TRUE)
 # All years assignments
 all_yr <- prec_data[, 2:13]
 # Season assignment
 jf <- prec_data[, 2:3]
 mam <- prec_data[, 4:6]
 jja <- prec_data[, 7:9]
 ond <- prec_data[, 11:13]
 jf_means[i] <- apply(jf, 1, mean)
mam_means[i] <- apply(mam, 1, mean)
 jja_means[i] <- apply(jja, 1, mean)
 ond_means[i] <-apply(ond, 1, mean)
 yr_means[i] <- apply(all_yr, 1, mean)
}

Jim

On Mon, Aug 24, 2015 at 3:01 AM, Peter Tuju <peterenos at ymail.com> wrote:
> Dear R users, I have fifty two (52) text files with the same dimensions (ie 31 by 13). Three sample of such data files are attached. I want to compute the rowMeans for each separate file for;(i) all the months
> (ii) For January and February
> (iii) For March, April and May
> (iv) For June, July and august
> (v) For October, November and December
> (vi) Plot the single mass curve for each file and season ie. plot(Year, cumsum(rowMeans([])))
> (vii) Plot Time series graphs for each file and per each season.
> The code I was trying to use is given below, and I investigated it and find that it does just for one only one file.How can I loop through all files?
> I kindly need your help.
>
> Thanks in advance!!
>
>
> rm(list = ls())
> setwd("/run/media/nwp-tma/+255767090047/analysis/R/R_sessions/R_sessions_prec/Rain_stn_data")# Import text filesprec_files <- list.files(pattern="*.txt")# Reading my files
> prec_files <- list.files(pattern = ".txt")
> for (i in 1:length(prec_files)){
>   prec_data = read.delim(prec_files[i], sep="\t",
> header = TRUE)  }
> #prec_data <- as.numeric(prec_data[, 2:13])
> # All years assignments
> all_yr <- prec_data[, 2:13]
> # Season assignment
> jf <- prec_data[, 2:3]
> mam <- prec_data[, 4:6]
> jja <- prec_data[, 7:9]
> ond <- prec_data[, 11:13]
> jf_means <- apply(jf, 1, mean)
> mam_means <- apply(mam, 1, mean)
> jja_means <- apply(jja, 1, mean)
> ond_means <-apply(ond, 1, mean)
> yr_mean <- apply(all_yr, 1, mean)
>
>
>  _____________
> Peter  E. Tuju
> Dar es Salaam
> T A N Z A N I A
> ----------------------
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list