簡體   English   中英

創建具有許多缺失值的每日平均值的問題

[英]Problems with creating daily mean with many missing values

我創建了這個 dataframe,對我的數據非常有代表性,抱歉代碼太長了。

library(lubridate)

datelist = seq(ymd_hms('1980-01-01 00:00:00'),ymd_hms('1980-07-01 00:00:00'), by = '60 mins')

df = data.frame(replicate(2,sample(0:130,4000,rep=TRUE)))
nbr_missing<-1000
y<-data.frame(row=sample(nrow(df),size = nbr_missing,replace = T),
              col=sample(ncol(df),size = nbr_missing,replace = T))

y<-y[!duplicated(y),]
df[as.matrix(y)]<-NA

df2 = data.frame(replicate(2,sample(0:130,369,rep=TRUE)))
nbr_missing<-500
xy<-data.frame(row=sample(nrow(df2),size = nbr_missing,replace = T),
               col=sample(ncol(df2),size = nbr_missing,replace = T))

xy<-xy[!duplicated(xy),]
df2[as.matrix(xy)]<-NA

fill1 = data.frame(matrix(NA, nrow = 4000, ncol = 2))
fill2 = data.frame(matrix(NA, nrow = 369, ncol = 2))

df_new1 = rbind(df, fill2)
df_new2 = rbind(fill1, df2)
df_new = cbind(df_new1, df_new2)

testframe = as.data.frame(cbind(datelist,df_new))
colnames(testframe) = c("Date", "ABC", "DEF", "GHI", "JKL")

我在計算每日平均值時遇到問題。 我多次將此代碼與其他數據一起使用,它總是很好用。 但在這里它似乎給了我錯誤的結果。 知道為什么以及如何解決這個問題嗎?

library(dplyr)
testframe1 = testframe %>%
  group_by(group = gl(n()/24, 24)) %>%
  summarise_at(-1, mean, na.rm = TRUE)

例如列 JKL,它在第一天的每小時數據中只包含 NA,但是當我創建平均值時,它給了我一個數字而不是 NA!

這是使用此命令時得到的示例。

每小時數據

錯誤的結果

我不確定dplyr代碼出了什么問題,您可以將by()方法與colMeans()一起使用。

res <- do.call(rbind, by(testframe[-1], as.Date(testframe1$Date), colMeans, na.rm=TRUE))
head(res)
#                 ABC      DEF GHI JKL
# 1980-01-01 74.25000 67.91304 NaN NaN
# 1980-01-02 52.70833 55.33333 NaN NaN
# 1980-01-03 65.37500 79.10000 NaN NaN
# 1980-01-04 48.61905 62.91667 NaN NaN
# 1980-01-05 62.34783 61.40909 NaN NaN
# 1980-01-06 80.38095 64.68182 NaN NaN

"group"你可以只是cbind()

res2 <- cbind(group=1:nrow(res), res)
head(res2)
#            group      ABC      DEF GHI JKL
# 1980-01-01     1 74.25000 67.91304 NaN NaN
# 1980-01-02     2 52.70833 55.33333 NaN NaN
# 1980-01-03     3 65.37500 79.10000 NaN NaN
# 1980-01-04     4 48.61905 62.91667 NaN NaN
# 1980-01-05     5 62.34783 61.40909 NaN NaN
# 1980-01-06     6 80.38095 64.68182 NaN NaN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM