忽略函数中的NA值 [英] Ignoring NA values in function

查看:65
本文介绍了忽略函数中的NA值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im writing my own function to calculate the mean of a column in a data set and then applying it using apply() but it only returns the first columns mean. Below is my code

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)

推荐答案

我们需要在 sum 中使用 na.rm = TRUE ,并在中使用它> apply 不起作用,因为 mymean 没有该参数

We need to use the na.rm=TRUE in the sum and using it in apply is not going to work as mymean doesn't have that argument

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)
 }

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

Note that colMeans can be used for getting the mean for each column.

这篇关于忽略函数中的NA值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆