[英]Dplyr: Renaming added columns in a tibble with rename() not working as intended
[英]Dplyr: Rename Tibble Output Columns With Factor Levels
長期潛伏者和首次海報。
我正在嘗試用 dplyr 標題 output 中的女孩、男孩和其他人重命名我的因子水平(1、2、3)。
這是代碼:
library(dplyr)
df1 %>%
dplyr::group_by(sex)%>%
dplyr::summarise(percent=100*n()/nrow(df1), n=n())
我的結果是:
# A tibble: 3 x 3
sexs percent n
<int> <dbl> <int>
1 1 52.1 731
2 2 47.1 661
3 NA 0.855 12
期望的結果是:
# A tibble: 3 x 3
sexs percent n
<int> <dbl> <int>
Girl 1 52.1 731
Boy 2 47.1 661
Other NA 0.855 12
期待任何建議。
謝謝!
我碰巧喜歡forcats
package,因為當我完成時,我實際上可以看到我做了什么。 另一種解決方案是在現有代碼之前簡單地添加到 pipe。
library(dplyr)
library(forcats)
sex <- sample(1:2, 100, replace = TRUE)
sex[[88]] <- NA
df1 <- data.frame(sex)
df1 %>%
mutate(newsex = fct_explicit_na(fct_recode(as_factor(sex),
Girl = "1",
Boy = "2" ),
na_level = "Other")) %>%
group_by(newsex, sex) %>%
summarise(percent = 100 * n() / nrow(df1), n=n())
#> # A tibble: 3 x 4
#> # Groups: newsex [3]
#> newsex sex percent n
#> <fct> <int> <dbl> <int>
#> 1 Girl 1 56 56
#> 2 Boy 2 43 43
#> 3 Other NA 1 1
由reprex package (v0.3.0) 於 2020 年 5 月 11 日創建
發布時請提供一些示例數據以供使用,它將幫助其他人測試並確保一切正常。 這個問題比較簡單,所以應該不是問題。
如果你想用任何其他數字替換 NA 你可以這樣做
df1 %>%
dplyr::mutate(sex = ifelse(is.na(sex), 0, sex),
sex = factor(sex,
levels = c(1,2,0),
labels = c("Girl", "Boy", "Other"))) %>%
dplyr::group_by(sex)%>%
dplyr::summarise(percent=100*n()/nrow(df1), n=n())
否則,您可以使用 case_when 分配因子,然后將列轉換為因子
df1 %>%
dplyr::mutate(sex = case_when(
sex == 1 ~ "Girl",
sex == 2 ~ "Boy",
is.na(sex) ~ "Other") %>%
as_factor(.)) %>%
dplyr::group_by(sex)%>%
dplyr::summarise(percent=100*n()/nrow(df1), n=n())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.