在R中一次根据所有变量的性别分布类型替换NA

时间:2018-07-14 11:28:42

标签: r dplyr plyr

在这里Replacing NA depending on distribution type of gender in R 我问如何根据发行类型替换NA。 Lstat的解决方案很棒

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

但是如果我有20个或更多的变量,该怎么办。该代码如何一次对所有变量起作用。即我不想写每个字符串

var1=ifelse
var2=ifelse
...
var20 ifelse

这是数据

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

1 个答案:

答案 0 :(得分:1)

您可以考虑使用s在多个列上应用相同的功能。

假设您要在dplyr::mutate_atemotion列上应用相同的功能,则解决方案可以写为:

IQ