【发布时间】:2018-07-14 11:28:41
【问题描述】:
这里,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))
【问题讨论】: