为什么我在计数和过滤后丢失了我的 NA (dplyr)
Why I loose my NA's after count and filter (dplyr)
我在计数后创建了以下数据框:
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
我要过滤“-1”。但是如果我对“-1”进行过滤,我也会失去我的 NA。即:
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
我需要我的 NA。
来自filter()的帮助文件
...Only rows where the condition evaluates to TRUE are kept...
NA != -1
[1] NA
由于您的条件 returns 为 NA(因此不正确),您需要第二个 OR 条件:
df %>%
filter(Procedure != -1 | is.na(Procedure))
您的问题已经得到解答,但如果您的列表较短(即,您不只是排除一个值),您可以使用 %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)
我在计数后创建了以下数据框:
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
我要过滤“-1”。但是如果我对“-1”进行过滤,我也会失去我的 NA。即:
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
我需要我的 NA。
来自filter()的帮助文件
...Only rows where the condition evaluates to TRUE are kept...
NA != -1
[1] NA
由于您的条件 returns 为 NA(因此不正确),您需要第二个 OR 条件:
df %>%
filter(Procedure != -1 | is.na(Procedure))
您的问题已经得到解答,但如果您的列表较短(即,您不只是排除一个值),您可以使用 %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)