[英]Recode NA factor with dplyr or forcats
我正在嘗試使用 tidyverse 中的forcats
或dplyr
tidyverse
將單個因子從NA
重新編碼為字符串。 我遇到的問題是我試圖改變的因素是一個NA
值,我遇到了一個錯誤。
我發現這個問題( R 如何將其中一個級別更改為 NA )正在將一個因素更改為NA
但我正在嘗試將其更改為 FROM NA
。
這是我嘗試過的:
library(dplyr)
df %>%
group_by(Units) %>%
summarize(Frequency = n(),
Total = sum(Responses, na.rm = T)) %>%
mutate(Units = recode_factor(Units, "No Response" = NA_character_))
# A tibble: 5 x 3
Units Frequency Total
<fct> <int> <dbl>
1 (0,3] 4 8
2 (3,10] 5 31
3 (10,30] 2 38
4 (100,Inf] 3 673
5 NA 1 0
Warning messages:
1: Problem with `mutate()` input `Units`.
i Unknown levels in `f`: NA
i Input `Units` is `fct_recode(Units, `No Response` = NA_character_)`.
2: Unknown levels in `f`: NA
和
library(forcats)
df %>%
group_by(Units) %>%
summarize(Frequency = n(),
Total = sum(Responses, na.rm = T)) %>%
mutate(Units = fct_recode(Units, "No Response" = NA_character_))
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 5 x 3
Units Frequency Total
<fct> <int> <dbl>
1 (0,3] 4 8
2 (3,10] 5 31
3 (10,30] 2 38
4 (100,Inf] 3 673
5 NA 1 0
樣本數據:
df <- structure(list(ID = c("000002", "000008", "000009", "000018",
"000021", "000033", "000045", "000051", "000064", "000067", "000070",
"000072", "000074", "000088", "000112"), Responses = c(18, 6,
300, 8, 7, 150, 6, 4, 2, 3, 20, NA, 223, 2, 1), Units = structure(c(3L,
2L, 5L, 2L, 2L, 5L, 2L, 2L, 1L, 1L, 3L, NA, 5L, 1L, 1L), .Label = c("(0,3]",
"(3,10]", "(10,30]", "(30,100]", "(100,Inf]"), class = "factor")), row.names = c(NA,
-15L), class = c("tbl_df", "tbl", "data.frame"))
使用專門編寫的fct_explicit_na
來處理NA
值。
library(dplyr)
library(forcats)
df %>%
group_by(Units) %>%
summarize(Frequency = n(),
Total = sum(Responses, na.rm = T)) %>%
mutate(Units = fct_explicit_na(Units, "No Response"))
# Units Frequency Total
#* <fct> <int> <dbl>
#1 (0,3] 4 8
#2 (3,10] 5 31
#3 (10,30] 2 38
#4 (100,Inf] 3 673
#5 No Response 1 0
您還可以在數據中包含新級別,然后使用replace
來更改NA
值。
levels(df$Units) <- c(levels(df$Units), "No Response")
df %>%
group_by(Units) %>%
summarize(Frequency = n(),
Total = sum(Responses, na.rm = T)) %>%
mutate(Units = replace(Units, is.na(Units), "No Response"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.