簡體   English   中英

當一個水平內的觀察數量低於限制時,因子的折疊水平

[英]Collapse levels of a factor when number of observations within a level are below a limit

我想要一種基於每個級別的觀察數量來折疊因子級別的方法。

例如,如果我在下面有一個動物因子列(四個級別:貓、狗、倉鼠、金魚)的小標題,我可以將少於 2 個觀察值的級別折疊成一個稱為“其他”的級別嗎?

# A tibble: 7 × 1
  animal  
  <fct>   
1 cat     
2 cat     
3 cat     
4 dog     
5 dog     
6 hamster 
7 goldfish

這應該導致以下...

# A tibble: 7 × 2
  animal   animal2
  <fct>    <fct>  
1 cat      cat    
2 cat      cat    
3 cat      cat    
4 dog      dog    
5 dog      dog    
6 hamster  other  
7 goldfish other  

我希望能夠調整截止值(例如,觀察次數少於 5 的組),理想情況下,這將使用 tidyverse 來完成。

您正在尋找forcats::fct_lump_min 崩潰到出現少於min'Other'級別:

library(forcats)
library(dplyr)
df %>% 
  mutate(animal2 = fct_lump_min(animal, min = 2),
         animal3 = fct_lump_min(animal, 3))

output

# A tibble: 7 × 3
  animal   animal2 animal3
  <fct>    <fct>   <fct>  
1 cat      cat     cat    
2 cat      cat     cat    
3 cat      cat     cat    
4 dog      dog     Other  
5 dog      dog     Other  
6 hamster  Other   Other  
7 goldfish Other   Other

暫無
暫無

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

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