2017-07-08 59 views
0

我要循环遍历R. CHR值ervery值的列表,我希望当我运行这段代码我得到的运行下一个代码CHR值在回路R变量

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 

有人知道它是如何工作的吗?

回答

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

谢谢,但我不想循环参数。我想循环NL14代码。我编辑了我的问题,使其更清楚。 –

+0

@ArjenKort这并没有说清楚。请问如何给出一个[可重现的例子](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) – h3rm4n

+0

@ArjenKort我已经更新了我的回答。你能检查一下是否有效吗? – h3rm4n