计算均值+选择的未定义列+ R时出错

时间:2019-11-13 07:34:41

标签: r dataframe mean

我有一个名为'目录'的数据框,其中有4列,即 a,b,c,d 。我需要根据输入找到b列或c列的均值。

b和c列均具有 NA和数值

TotalMean<- function(directory, pollutant = "b", id = 1:10)
{
    mean(subset(directory, ID=  id, select = directory[[pollutant]]), na.rm = TRUE)
}

TotalMean<- function(directory, pollutant = "b", id = 1:10)
{
    mean(subset(directory, ID=  id, select = directory$pollutant), na.rm = TRUE)
}

TotalMean<- function(directory, pollutant = "b", id = 1:10)
{
    mean(subset(directory, ID=  id, select = directory[,pollutant]), na.rm = TRUE)
}

我已经尝试了所有上述功能。但是,它给了我以下错误。

由于我是R编程的新手,所以我不确定为什么会这样。任何帮助将不胜感激。

预先感谢

1 个答案:

答案 0 :(得分:0)

您不需要子集,只需执行以下操作

TotalMean <- function(directory, pollutant = "b", id = 1:10) {
    mean(directory[id, pollutant], na.rm=TRUE)
}

directory <- data.frame("a" = c(1,NA,2), "b" = c(NaN,2,3))
print(TotalMean(directory,"a"))
print(TotalMean(directory,"b"))