為什麼即使在 R 中使用 dplyr 將 na.rm 設定為 TRUE,均值也是 NaN?


如果使用 dplyr 包將 na.rm 設定為 TRUE,則統計運算的輸出結果為 NaN。為避免這種情況,我們需要排除 na.rm。請按照以下步驟瞭解兩者之間的區別:

  • 首先,建立一個數據框。
  • 如果資料框中存在 NA,則使用 na.rm 設定為 TRUE 來彙總資料框。
  • 不將 na.rm 設定為 TRUE 來彙總資料框。

建立資料框

讓我們建立一個如下所示的資料框:

 線上演示

Group&li;-rep(c("First","Second","Third"),times=c(3,10,7))
Response&li;-rep(c(NA,3,4,5,7,8),times=c(3,2,5,2,4,4))
df&li;-data.frame(Group,Response)
df

執行上述指令碼後,將生成以下輸出(由於隨機化,此輸出將在您的系統上有所不同):

Group Response
1 First NA
2 First NA
3 First NA
4 Second 3
5 Second 3
6 Second 4
7 Second 4
8 Second 4
9 Second 4
10 Second 4
11 Second 5
12 Second 5
13 Second 7
14 Third 7
15 Third 7
16 Third 7
17 Third 8
18 Third 8
19 Third 8
20 Third 8

使用 na.rm 設定為 TRUE 彙總資料框

載入 dplyr 包並使用每個組的 Response 均值彙總資料框 df:

library(dplyr)
Group<-rep(c("First","Second","Third"),times=c(3,10,7))
Response<-rep(c(NA,3,4,5,7,8),times=c(3,2,5,2,4,4))
df<-data.frame(Group,Response)
df%>%group_by(Group)%>%summarise(mean=mean(Response,na.rm=TRUE))
# A tibble: 3 x 2
Group mean
  <chr> <dbl>
1 First NaN
2 Second 4.3
3 Third 7.57

不將 na.rm 設定為 TRUE 彙總資料框

不將 na.rm 設定為 TRUE,使用每個組的 Response 均值彙總資料框 df:

Group<-rep(c("First","Second","Third"),times=c(3,10,7))
Response<-rep(c(NA,3,4,5,7,8),times=c(3,2,5,2,4,4))
df<-data.frame(Group,Response)
df%>%group_by(Group)%>%summarise(mean=mean(Response))
# A tibble: 3 x 2
Group mean
  <chr> <dbl>
1 First NA
2 Second 4.3
3 Third 7.57

更新於:2021年8月13日

777 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.