R Easy版本中的折叠列

问题描述

我知道已经有一些与此问题类似的问题,但是我是r的初学者,我无法理解答案!如果您能够为我的问题提供一个简单而不是那么复杂的答案,我将不胜感激!

我正在尝试折叠数据框中某列中的类别,其摘要如下所示(category = n):

1-Self = 62
2-Mother = 0
3-Father = 43
4-Grandfather = 142
5-Grandmother = 17
6-Uncle = 1
7-brother = 2
8-Husband = 5
9-Aunt = 0
10-Sister = 2
11-CommunityInfluencer = 1
12-ReligIoUsfigure = 0
13-Other = 4
14-N/A = 9

我想合并6-14类,但是它们都在同一列中,我该怎么做?如果您能提供一种简单的编码方法,我将不胜感激!

谢谢!

解决方法

使用forcats::fct_other,您可以指定要将哪些类别合并为“其他”类别

例如:

library(tidyverse)

drop_cats <- c("Naboo","Stewjon")

starwars %>%
  mutate(homeworld =  fct_other(homeworld,drop = drop_cats)) 

A tibble: 87 x 13
   name       height  mass hair_color   skin_color eye_color birth_year gender homeworld species films  vehicles starships
   <chr>       <int> <dbl> <chr>        <chr>      <chr>          <dbl> <chr>  <fct>     <chr>   <list> <list>   <list>   
 1 Luke Skyw…    172    77 blond        fair       blue            19   male   Tatooine  Human   <chr … <chr [2… <chr [2]>
 2 C-3PO         167    75 NA           gold       yellow         112   NA     Tatooine  Droid   <chr … <chr [0… <chr [0]>
 3 R2-D2          96    32 NA           white,bl… red             33   NA     Other     Droid   <chr … <chr [0… <chr [0]>
 4 Darth Vad…    202   136 none         white      yellow          41.9 male   Tatooine  Human   <chr … <chr [0… <chr [1]>
 5 Leia Orga…    150    49 brown        light      brown           19   female Alderaan  Human   <chr … <chr [1… <chr [0]>
 6 Owen Lars     178   120 brown,grey  light      blue            52   male   Tatooine  Human   <chr … <chr [0… <chr [0]>
 7 Beru Whit…    165    75 brown        light      blue            47   female Tatooine  Human   <chr … <chr [0… <chr [0]>
 8 R5-D4          97    32 NA           white,red red             NA   NA     Tatooine  Droid   <chr … <chr [0… <chr [0]>
 9 Biggs Dar…    183    84 black        light      brown           24   male   Tatooine  Human   <chr … <chr [0… <chr [1]>
10 Obi-Wan K…    182    77 auburn,whi… fair       blue-gray       57   male   Other     Human   <chr … <chr [1… <chr [5]>
# … with 77 more rows

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...