【问题标题】:R: Replacing NA values by mean of hour with dplyrR:用 dplyr 以小时为单位替换 NA 值
【发布时间】:2023-04-02 01:48:02
【问题描述】:

我正在学习 R 中的 dplyr 包,我非常喜欢它。但现在我正在处理数据中的 NA 值。

我想用相应小时的平均值替换任何 NA,例如这个非常简单的例子:

#create an example
day = c(1, 1, 2, 2, 3, 3)
hour = c(8, 16, 8, 16, 8, 16)
profit = c(100, 200, 50, 60, NA, NA)
shop.data = data.frame(day, hour, profit)

#calculate the average for each hour
library(dplyr)
mean.profit <- shop.data %>%
  group_by(hour) %>%
  summarize(mean=mean(profit, na.rm=TRUE))

> mean.profit
Source: local data frame [2 x 2]

  hour mean
1    8   75
2   16  130

我可以使用 dplyr transform 命令将利润中第 3 天的 NA 替换为 75(8:00)和 130(16:00)吗?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    试试

      shop.data %>% 
                 group_by(hour) %>% 
                 mutate(profit= ifelse(is.na(profit), mean(profit, na.rm=TRUE), profit))
    
      #   day hour profit
      #1   1    8    100
      #2   1   16    200
      #3   2    8     50
      #4   2   16     60
      #5   3    8     75
      #6   3   16    130
    

    或者你可以使用replace

      shop.data %>% 
                group_by(hour) %>%
                mutate(profit= replace(profit, is.na(profit), mean(profit, na.rm=TRUE)))
    

    【讨论】:

    • 我来这里是因为我没有注意到我忘记了钥匙:na.rm = TRUE
    【解决方案2】:

    带有基本函数的(不太优雅的)方法:

    transform(shop.data, 
              profit = ifelse(is.na(profit), 
                              ave(profit, hour, FUN = function(x) mean(x, na.rm = TRUE)), 
                              profit))
    
    #   day hour profit
    # 1   1    8    100
    # 2   1   16    200
    # 3   2    8     50
    # 4   2   16     60
    # 5   3    8     75
    # 6   3   16    130
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多