0

I want to loop over a list of chr values in R. For ervery value I want to run the next code

for (locatie in Locaties){ # Locaties is a list of character values ("NL14_20076" "NL14_20077" etc)
  Data_ammoniak <- subset(paste0("Data_",locatie), Parameter == "ammoniak")
  # I want to make a dataset with only ammoniak data out of a dataset called "Data_NL14_20076"
  # So I want to use the value from the list
  ggplot(Data_ammoniak, aes(x = Begindatum, y = Meetwaarde_n)) +
    geom_point() +
    geom_line() +
    labs(x = "Datum",
         y = "Meetwaarde",
         title = paste0(locatie, "Ammoniak")) # This one is working I think

  ggsave(paste0("C:/Temp/LTO_Noord/",locatie,"_Ammoniak.png"), #This one is working as well I think
         width = 30,
         height = 20,
         units = "cm")
} 

When I run this code I get the following error:

Error in subset.default(paste0("Data_", locatie), Parameter == "ammoniak") : 
  object 'Parameter' not found   

Does somebody know how it will work?

1 Answers1

0

You can do that with lapply. The following code should work:

lapply(Locaties, function(l) {
  dat <- get(paste0("Data_",l))
  ggplot(dat[dat$Parameter == "ammoniak", ], aes(x = Begindatum, y = Meetwaarde_n)) +
    geom_point() +
    geom_line() +
    labs(x = "Datum", 
         y = "Meetwaarde", 
         title = paste0(l, " Ammoniak")) +
    ggsave(paste0("C:/Temp/LTO_Noord/",l,"_Ammoniak.png"), 
           width = 30, 
           height = 20, 
           units = "cm")
})
h3rm4n
  • 4,126
  • 15
  • 21
  • Thank you, but i do not want to loop over the parameters. I want to loop over the NL14 codes. I edited my question to make it more clear. – Arjen Kort Jul 08 '17 at 11:15
  • @ArjenKort That doesn't make it clearer. Please the Q&A on how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) – h3rm4n Jul 08 '17 at 11:54
  • @ArjenKort I have updated my answer. Could you check if that works? – h3rm4n Jul 08 '17 at 13:23
  • @ArjenKort great! see also [this help page](https://stackoverflow.com/help/someone-answers) – h3rm4n Jul 08 '17 at 13:40