【问题标题】:Opening files in R [duplicate]在R中打开文件[重复]
【发布时间】:2015-02-13 05:59:20
【问题描述】:

假设一个目录有 100 个文件。我应该如何通过 R 代码打开 50-60 范围内的文件? 我尝试使用 for 循环,但如何通过 for 循环打开名称为 50,51,52...60 的文件?

编写一个名为“pollutantmean”的函数,用于计算指定监视器列表中污染物(硫酸盐或硝酸盐)的平均值。函数“pollutantmean”接受三个参数:“directory”、“pollutant”和“id”。给定一个向量监视器 ID 号,“pollutantmean”从“目录”参数中指定的目录中读取该监视器的颗粒物数据,并返回所有监视器中污染物的平均值,忽略编码为 NA 的任何缺失值。

【问题讨论】:

标签: r file directory


【解决方案1】:

假设文件在working directory

pollutantmean <- function(pathtodirectory, pollutant, id=1:332){
    files <- sprintf('%s/%03d.csv', pathtodirectory,id)
    lst <- vector('list', length(id))
    m1 <- vector('numeric', length(id))
     for(i in seq_along(lst)){
      lst[[i]] <- read.csv(files[i])
       if(pollutant=='sulfate'){
         m1[i] <- mean(lst[[i]]$sulfate, na.rm=TRUE)
       }

       if(pollutant=='nitrate'){
          m1[i] <- mean(lst[[i]]$nitrate, na.rm=TRUE)
         }
       }
    return(list(m1, mean(m1)))          
 }       


pollutantmean(getwd(), 'nitrate',1:5)
pollutantmean(getwd(), 'sulfate',1:5)[[1]]

【讨论】:

    【解决方案2】:

    以下是我在学习课程时解决问题的方法:

    pollutantmean <- function(directory=getwd(), pollutant, id = 1:332) {
      filetotals <- 0
      observationnumber <- 0
      for(i in id) {
        csvfile <- sprintf("%03d.csv", i)
        filepath <- file.path(directory, csvfile)
        readcsvfile <- read.csv(filepath)
        justpollutant <- readcsvfile[[pollutant]]
        purepollutant <- justpollutant[!is.na(justpollutant)]
        observationnumber <- observationnumber + length(purepollutant) 
        sumpollutant <- sum(purepollutant)
        filetotals <- filetotals + sumpollutant
      }
      print(filetotals)
      print(observationnumber)
      filetotals / observationnumber
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-25
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 2019-02-11
      相关资源
      最近更新 更多