gpt4 book ai didi

删除 dplyr 管道中的 NA

转载 作者:行者123 更新时间:2023-12-03 05:18:24 25 4
gpt4 key购买 nike

我尝试使用 dplyr 管道从子集中删除 NA。我的回答是否表明我错过了一步?我正在尝试学习如何使用 dplyr 编写函数:

> outcome.df%>%
+ group_by(Hospital,State)%>%
+ arrange(desc(HeartAttackDeath,na.rm=TRUE))%>%
+ head()
Source: local data frame [6 x 5]
Groups: Hospital, State
                           Hospital State HeartAttackDeath1     ABBEVILLE AREA MEDICAL CENTER    SC               NA2        ABBEVILLE GENERAL HOSPITAL    LA               NA3      ABBOTT NORTHWESTERN HOSPITAL    MN             12.34   ABILENE REGIONAL MEDICAL CENTER    TX             17.25        ABINGTON MEMORIAL HOSPITAL    PA             14.36 ABRAHAM LINCOLN MEMORIAL HOSPITAL    IL               NAVariables not shown: HeartFailureDeath (dbl), PneumoniaDeath  (dbl)

最佳答案

我不认为 desc 采用 na.rm 参数...我实际上很惊讶当你给它一个参数时它不会抛出错误。如果您只想删除 NA,请使用 na.omit (base) 或 tidyr::drop_na:

outcome.df %>%
na.omit() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()

library(tidyr)
outcome.df %>%
drop_na() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()

如果您只想从 HeartAttackDeath 列中删除 NA,请使用 is.na 进行过滤,或使用 tidyr::drop_na:

outcome.df %>%
filter(!is.na(HeartAttackDeath)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()

outcome.df %>%
drop_na(HeartAttackDeath) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()

正如欺骗中所指出的,也可以使用 complete.cases ,但放入链中有点棘手,因为它接受数据帧作为参数,但返回索引向量。所以你可以像这样使用它:

outcome.df %>%
filter(complete.cases(.)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()

关于删除 dplyr 管道中的 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665319/

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