【问题标题】:Error when looping: attempt to select more than one element in vectorIndex循环时出错:尝试在 vectorIndex 中选择多个元素
【发布时间】:2022-01-19 12:16:09
【问题描述】:

我是使用 R 编码的新手,我使用的是大型数据集。 我正在尝试编写执行以下操作的代码:

  1. 获取我文件夹中所有文件的所有路径
  2. 提取文件名(因为我想在输入文件之后命名我的图)
  3. 读入我文件夹中的所有文件(这些都是 .csv 文件)
  4. 通过绘制地下水位与年份的关系,为每个 .csv 文件绘制图表 --> 然后这些图应该得到输入文件的标题,并以相同的名称存储。

例如当我的文件名为 211210.csv,那么标题应该是 211210 并存储为 211210.png

这是我知道的代码。正如我所说,我是 R 新手,我试图解决我在代码中可能遇到的问题,但我仍然遇到新的错误。有没有人可以解释一下问题出在哪里以及如何解决。

library(fs)
library(ggplot2)
library(tidyverse)

#Opening path to my data

filepath <- fs::dir_ls("D:/Desktop/Masterarbeit/Daten/Test/")

# Get name of files 
name <- basename(filepath) 


#Read every single files 
file_content <- list()

for (i in seq_along(filepath)){
  path <- filepath
  
  file_content[[i]] <- read.csv(
    file = filepath[[i]], header = TRUE
    
    )
}

file_content <- set_names(file_content, filepath)


#Plot the diagram with gwl against year for each file, title = name of each file and store it in a seperat folder with the name of the input file

for (i in file_content){
  mypath <- file.path("D:/Desktop/Masterarbeit/Daten/Results/", paste("Messstelle_", name[[i]], ".png", sep = ""))
  png(file=mypath)
    mytitle = paste("Messstelle", name[[i]])
  plot(i$year, i$gwl,
     pch = 19, #--> solid circle
     cex = 1.5, #--> make 150% size
     main = name[[i]],
     xlab = "Year",
     ylab = "Ground water level",
)
  dev.off()
}


【问题讨论】:

    标签: r loops storage extract


    【解决方案1】:

    首先,为了提高效率,我宁愿在一个循环中完成所有事情。其次,我会避免使用不必要的软件包,例如fs(Base R 有一个很好的list.files 函数来列出文件夹中的所有文件)第三,我会遍历文件的名称而不是数字向量,例如:

    filepath <- "D:/Desktop/Masterarbeit/Daten/Test/"
    files <- list.files(filepath, pattern=".csv")
    
    #Iterate through every single file 
    for (file in files){
      
      name2store <- strsplit(file, "[.]")[[1]][1]
      
      path2read <- file.path(filepath, file) 
      data <- read.csv(file =path2read, header = TRUE)
     
      mypath <- file.path("D:/Desktop/Masterarbeit/Daten/Results/", paste("Messstelle_", name2store, ".png", sep = ""))
      
      png(file=mypath)
      mytitle = paste("Messstelle", name2store)
      plot(data$year, data$gwl,
           pch = 19, #--> solid circle
           cex = 1.5, #--> make 150% size
           main = name2store,
           xlab = "Year",
           ylab = "Ground water level",
      )
      dev.off()
    }
    

    【讨论】:

    • 非常感谢。它运作良好。所以我基本上应该使用不同的功能。只是为了理解,你能告诉我为什么我在错误中运行我的代码以及我该如何解决它?我想了解我做错了什么。
    • 运行您的代码版本时会收到哪些错误消息?
    • 这个:名称错误[[i]]:尝试在vectorIndex中选择多个元素
    • 您在代码中定义name &lt;- basename(filepath),然后,您正在评估name 的元素,因为它将是list() 通过name[[i]]。这不起作用。你应该在你的for循环中使用ì来提取name2store
    猜你喜欢
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2023-04-04
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    相关资源
    最近更新 更多