【问题标题】:R code - Pollutant Mean is producing NaNsR 代码 - 污染物平均值正在产生 NaN
【发布时间】:2015-05-15 03:06:01
【问题描述】:

我非常接近完成这个 R 程序,但结果一直给我 NaN。它应该在一堆 csv 文件中找到硝酸盐或硫酸盐的平均值。有谁知道代码可能出错的地方吗?以下是程序说明。这似乎很不言自明,只是我有点难过。如果您需要更多详细信息,请告诉我。谢谢

pollutantmean <- function(directory, pollutant, id = 1:332) {
        ## 'directory' is a character vector of length 1 indicating
        ## the location of the CSV files

        ## 'pollutant' is a character vector of length 1 indicating
        ## the name of the pollutant for which we will calculate the
        ## mean; either "sulfate" or "nitrate".

        ## 'id' is an integer vector indicating the monitor ID numbers
        ## to be used

        ## Return the mean of the pollutant across all monitors list
        ## in the 'id' vector (ignoring NA values)
}

pollutantmean = function(directory, pollutant, id = 1:332) {
            files_polm = list.files(directory, full.names = TRUE)
            dat_3 = numeric()
            for (x in id) {
                    dat_3 = rbind(dat_3, read.csv(files_polm[x]))
            }
            if (pollutant == "sulfate") {
                    sub_pol = dat_3[which(dat_3[, "sulfate"] == "sulfate"), ]
                    mean(sub_pol[, "sulfate"], na.rm = TRUE)
            }
            else if (pollutant == "nitrate") {
                    sub_pol = dat_3[which(dat_3[, "nitrate"] == "nitrate"), ]
                    mean(sub_pol[, "nitrate"], na.rm = TRUE)
            }
            else {
                    print("Try Again")
            }
    }

【问题讨论】:

  • 你能把这个设为reproducible example吗?这将使我们更容易尝试并找出问题所在。
  • 如果你让每个步骤都工作并然后将它放入一个函数中会更容易调试
  • 用文字描述你想要什么也会有所帮助。您真的需要查看名为“硫酸盐”的列来查找值为“硫酸盐”的行吗?没有看到你的数据就不可能说出来。
  • 我用解释编辑了我上面的原始帖子。我很抱歉没有提供更多细节。谢谢。
  • 您在某处有一个空组。 mean(numeric(0))NaN ...

标签: r function dataset mean


【解决方案1】:

我编辑了您的代码,假设在每个 .csv 文件中您的“硝酸盐”或“硫酸盐”列包含数字或整数数据类型,即每种物质的数量/浓度。

我还修改了 for 循环,使其与您的 .csv 文件结构更加一致。这是代码,希望它有效 - 如果没有,请编辑以引入您的 .csv 文件之一的 str() 函数的输出

pollutantmean = function(directory, pollutant, id = 1:332) {
 files_polm = list.files(directory, full.names = TRUE)
 dat_3 = numeric()
 for (x in id) {
   if (x==id[1]) {
     dat_3 = read.csv(files_polm[x])
   } else{
     dat_3 = rbind(dat_3, read.csv(files_polm[x])) 
   }

 }
 if (pollutant == "sulfate") {
    mean(sub_pol[, "sulfate"], na.rm = TRUE)
 } else if (pollutant == "nitrate") {
    mean(sub_pol[, "nitrate"], na.rm = TRUE)
 } else {
    print("Try Again")
 }
}

【讨论】:

  • 非常感谢。我正在根据我所做的分析代码。
  • 仍然得到 NaN。从你给我的代码中,我几乎只是再次定义了“sub_pol”,这样我就可以获得“硫酸盐”或“硝酸盐”的子集
  • @AlvinvanderKuech,所以你设法解决了吗?如果没有,一些示例数据或 dat_3 变量上的 str() 函数的输出将有助于修改您的代码,或了解哪里出了问题
  • 谢谢,我会一步一步来。这是查看不起作用的最佳方法。这是我需要学习的东西,所以不妨跳进去。
猜你喜欢
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 2019-06-20
  • 1970-01-01
  • 2018-05-28
相关资源
最近更新 更多