忽略函数中的 NA 值

J. *_*ton 2 r function na

我正在编写自己的函数来计算数据集中列的平均值,然后使用它来应用它,apply()但它只返回第一列的平均值。下面是我的代码:

mymean <- function(cleaned_us){
  column_total = sum(cleaned_us)
  column_length = length(cleaned_us)
  return (column_total/column_length)
}

Average_2 <- apply(numeric_clean_usnews,2,mymean,na.rm=T)
Run Code Online (Sandbox Code Playgroud)

akr*_*run 6

我们需要na.rm=TRUE在 the 中使用 the sum,但在 in 中使用它apply是行不通的,因为mymean没有这个参数

mymean <- function(cleaned_us){
   column_total = sum(cleaned_us, na.rm = TRUE) #change
   column_length = sum(!is.na(cleaned_us)) #change
  return(column_total/column_length)
 }
Run Code Online (Sandbox Code Playgroud)

请注意,colMeans可用于获取mean每列的 。