chr值作为for循环R的变量

时间:2017-07-08 11:04:18

标签: r loops for-loop character

我想在R中循环一个chr值列表 对于非常值,我想运行下一个代码

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")
} 

当我运行此代码时,我收到以下错误:

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

有人知道它会如何起作用吗?

1 个答案:

答案 0 :(得分:0)

您可以使用lapply执行此操作。以下代码应该有效:

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")
})