gpt4 book ai didi

R:用 dplyr 按小时替换 NA 值

转载 作者:行者123 更新时间:2023-12-04 01:36:23 26 4
gpt4 key购买 nike

我正在学习 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 变换命令将利润中第 3 天的 NA 替换为 75(8:00)和 130(16:00)吗?

最佳答案

尝试

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

关于R:用 dplyr 按小时替换 NA 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26336122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com