根据R中性别的分布类型替换NA [英] Replacing NA depending on distribution type of gender in R

查看:105
本文介绍了根据R中性别的分布类型替换NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在此处选择NA值

data[data=="na"] <- NA
data[!complete.cases(data),]

我必须替换它,但要取决于发行版的类型. 如果使用Shapiro.test通过不正常的变量进行分布, 然后必须用中位数代替缺失值, 如果正常,则用平均值代替. 但是每个性别的分布情况(1个女孩,2个男人)

i must replace it, but depending on type of distribution. If using Shapiro.test the distribution by variables not normal, then missing value must be replace by median, If it's normal, than replace by mean. But distribution for each gender(1 girl, 2 -man)

data=structure(list(sex = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), emotion = c(20L, 
15L, 49L, NA, 34L, 35L, 54L, 45L), IQ = c(101L, 98L, 105L, NA, 
123L, 120L, 115L, NA)), .Names = c("sex", "emotion", "IQ"), class = "data.frame", row.names = c(NA, 
-8L))

所需的输出

sex emotion IQ
1   20  101
1   15  98
1   49  105
1   28  101
2   34  123
2   35  120
2   54  115
2   45  119

推荐答案

以下代码将根据Shapiro测试替换NA值:

Following code will replace NA values according to the Shapiro Test:

library(dplyr)

data %>% 
 group_by(sex) %>%
 mutate(
  emotion = ifelse(!is.na(emotion), emotion,
   ifelse(shapiro.test(emotion)$p.value > 0.05,
    mean(emotion, na.rm=TRUE), quantile(emotion, na.rm=TRUE, probs=0.5) ) ),
  IQ = ifelse(!is.na(IQ), IQ,
   ifelse(shapiro.test(IQ)$p.value > 0.05,
    mean(IQ, na.rm=TRUE), quantile(IQ, na.rm=TRUE, probs=0.5) )
  )
 ) 

这篇关于根据R中性别的分布类型替换NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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