简体   繁体   English

为什么我在计数和过滤后不放NA(dplyr)

[英]Why I loose my NA's after count and filter (dplyr)

I have the following data frame which I create after a count: 我有一个计数后创建的以下数据框:

df <- structure(list(Procedure_priority = structure(c(4L, 1L, 2L, 3L, NA, 5L),
                                                    .Label = c("A", "B", "C", "D", "-1"), 
                                                    class = "factor"), n = c(10717L, 4412L, 2058L, 1480L, 323L, 2L)), 
                class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L), .Names = c("Procedure", "n"))


# A tibble: 6 x 2
  Procedure     n
  <fct>     <int>
1 D         10717
2 A          4412
3 B          2058
4 C          1480
5 <NA>        323
6 -1            2

I want to filter the "-1". 我想过滤“ -1”。 But if I make a filter on "-1" I also loose my NA. 但是,如果我对“ -1”进行过滤,我也会失去NA。 That is: 那是:

df %>% 
  filter(Procedure!="-1")

# A tibble: 4 x 2
  Procedure     n
  <fct>     <int>
1 D         10717
2 A          4412
3 B          2058
4 C          1480

I need my NA's. 我需要我的NA。

From the Help file of filter() 从filter()的帮助文件中

...Only rows where the condition evaluates to TRUE are kept... ...仅保留条件评估为TRUE的行...

NA != -1
[1] NA

Since your condition returns a NA (hence not TRUE) you need a second OR condition: 由于您的条件返回一个NA(因此不是TRUE),因此您需要第二个OR条件:

df %>% 
  filter(Procedure != -1 | is.na(Procedure))

Your question is already answered, but if you have a shorter list (ie, you are not just excluding one value) you can use %in% and still keep NA's. 您的问题已经得到回答,但是如果列表较短(即,您不仅在排除一个值),还可以使用%in%并仍然保留NA。

# Keep A, D, and NA; aka dropping B, C, and -1
keep_these_procs <- c("A", "D", NA)

df %>%
  filter(Procedure %in% keep_these_procs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM