【问题标题】:Replacing NA depending on distribution type of gender for all variable at once in R在 R 中一次根据所有变量的性别分布类型替换 NA
【发布时间】: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))

【问题讨论】:

    标签: r dplyr plyr


    【解决方案1】:

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

    假设,您想在 emotionIQ 列上应用相同的函数,那么解决方案可以写成:

    library(dplyr)
    data %>% 
      group_by(sex) %>%
      mutate_at(vars(c("emotion", "IQ")), 
                funs(ifelse(!is.na(.), ., ifelse(shapiro.test(.)$p.value > 0.05,
                                 mean(., na.rm=TRUE), quantile(., na.rm=TRUE, probs=0.5)))))
    
    # # A tibble: 8 x 3
    # # Groups: sex [2]
    #     sex emotion    IQ
    #   <int>   <dbl> <dbl>
    # 1     1    20.0 101  
    # 2     1    15.0  98.0
    # 3     1    49.0 105  
    # 4     1    28.0 101  
    # 5     2    34.0 123  
    # 6     2    35.0 120  
    # 7     2    54.0 115  
    # 8     2    45.0 119 
    

    【讨论】:

    • MKR,非常感谢你。如何做到这一点此代码不考虑组?我将使用您的解决方案,但我想测试一个假设,而不考虑性别
    • @varimax 只需删除 group_by 行,它将执行 data.frame 中的所有行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2020-11-14
    • 1970-01-01
    相关资源
    最近更新 更多