【问题标题】:chr values as variable in for loop Rchr值作为for循环R中的变量
【发布时间】:2017-07-08 11:04:18
【问题描述】:

我想遍历 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   

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

【问题讨论】:

    标签: r loops for-loop character


    【解决方案1】:

    您可以使用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")
    })
    

    【讨论】:

    • 谢谢,但我不想循环参数。我想遍历 NL14 代码。我编辑了我的问题以使其更清楚。
    • @ArjenKort 这并没有让它更清楚。请Q&A关于如何给予reproducible example
    • @ArjenKort 我已经更新了我的答案。你能检查一下这是否有效吗?
    • @ArjenKort 太棒了!另见this help page
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多