簡體   English   中英

R - 將 forcats fct_collapse 與 tidyselect 選擇助手結合使用

[英]R - Using forcats fct_collapse in combination with tidyselect selection helpers

我有一個雜亂的因子變量,其中包含各種非常相似的因子水平(例如,由拼寫錯誤、略有不同的措辭等引入)。 我正在嘗試使用來自 forcats package 的 fct_collapse function 將該因素合並為四個主要類別。

然而,考慮到可變性的數量,我想將 fct_collapse function 與 tidy selct 中的選擇助手結合起來,例如 starts_with() 和 contains()。

這是一個簡單的可重現示例:我想將具有不同級別的單個因子列減少到兩個因子級別“a”和“b”。

 factor_df<-tibble(my_factor=factor(c("a_1","a_2","a_x","a_factor","a_factor","also_factor_a", 
                                      "1_b_1","2_b_2","xx_b_xx")))

我不想列出每一個因素,而是盡可能使用選擇助手來為我做這件事。 但是,以下代碼會引發錯誤:

factor_df%>%
            mutate(new_fct=fct_collapse(factor_df$my_factor,
                                        a=c(starts_with("a_"), "also_factor_a"),
                                        b=c(tidyselect::contains("_b_"))))

錯誤:必須在選擇function 中使用starts_with() 。我參見https://tidyselect.r-lib.org/reference/faq-selection-context.html

(該鏈接並不過分有用。)如何使用輔助函數完成此操作?

starts_with來自dplyr ,它正在尋找列名而不是列中的值。 我們可以使用grepstartsWith

library(dplyr)
library(forcats)
factor_df %>% 
   mutate(new_fct = fct_collapse(my_factor,
     a = c(levels(my_factor)[startsWith(levels(my_factor), "a_")], 
      "also_factor_a"), b = grep("_b_", levels(my_factor), value = TRUE)))

-輸出

# A tibble: 9 × 2
  my_factor     new_fct
  <fct>         <fct>  
1 a_1           a      
2 a_2           a      
3 a_x           a      
4 a_factor      a      
5 a_factor      a      
6 also_factor_a a      
7 1_b_1         b      
8 2_b_2         b      
9 xx_b_xx       b   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM