0

I have written a R code for a project. Since I have many data files, it is somewhat hard to rename the files everytime. Has anyone an idea to create a loop with R?

My code is (I is the number which has to be replaced by the loop):

data1 <- read_csv("../**I**_FILE.csv")
data2 <- read_excel("Nr**I**.xlsx")

#Merge
a <- function(s) (trunc(chron(s),"00:36:00"))
z1<- read.zoo(data1, header=TRUE, FUN=a, agg=mean)
z2<- read.zoo(data2, header=TRUE, FUN=a, agg=mean)

merged <- merge(z1,z2)

plot(merged$z2,merged$z1,
     main="**I**")

*THIS PLOT HAS TO BE SAVED as "**I**.png/tiff/whatever"*


write.csv(merged, file="**I**.csv",
          row.names = TRUE)
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Maik125
  • 15
  • 3
  • 4
    Does this answer your question? [how to use paste in for loops](https://stackoverflow.com/questions/40450541/how-to-use-paste-in-for-loops) – slamballais May 16 '21 at 09:55
  • 1
    If you're asking on how to write a for-loop, there are many good tutorials on that available, like [this one](https://www.guru99.com/r-for-loop.html). – slamballais May 16 '21 at 09:57

1 Answers1

1

if "I" is a numeric index for example 1,2,3... you could use paste0 and for Here an example with exactly the same code you posted

for (i in 1:X) {
  data1 <- read_csv(paste0("../",i,"_FILE.csv"))
  data2 <- read_excel(paste0("Nr",i,".xlsx"))
  
  #Merge
  a <- function(s) (trunc(chron(s),"00:36:00"))
  z1<- read.zoo(data1, header=TRUE, FUN=a, agg=mean)
  z2<- read.zoo(data2, header=TRUE, FUN=a, agg=mean)
  
  merged <- merge(z1,z2)
  
  png(paste0(i,".png/tiff/whatever"))
  print(plot(merged$z2,merged$z1,
       main=i))
  dev.off()
    write.csv(merged, file=paste0(i,".csv"),
              row.names = TRUE)
}

I m not sure if the path of your plots is correct. Myabe is better somethings like png(paste0("path/to/your/folder/",i,".png"))

Elia
  • 2,210
  • 1
  • 6
  • 18