如何在R中不重复地使用FORCAT重新编码多个值
我想使用如何在R中不重复地使用FORCAT重新编码多个值,r,forcats,R,Forcats,我想使用forcats重新编码系数x,使用像yes=“bad”、yes=“2”、no=“3”、no=“good”这样的映射,但不重复代码。 类似于yes=levels(x)[1:2]和no=levels(x)[3:4] <!-- language-all: lang-r --> library(forcats) x <- factor(c("bad", "2", "2", "good&q
forcats
重新编码系数x
,使用像yes=“bad”、yes=“2”、no=“3”、no=“good”这样的映射,但不重复代码。
类似于yes=levels(x)[1:2]
和no=levels(x)[3:4]
<!-- language-all: lang-r -->
library(forcats)
x <- factor(c("bad", "2", "2", "good", "3", "3", "3", "good"),
levels = c("bad",2,3,"good"))
fct_recode(x, yes = "bad", yes = "2", no = "3", no = "good")
#> [1] yes yes yes no no no no no
#> Levels: yes no
# I don't want to repeat yes and no
levels(x)[1:2] # should be yes
#> [1] "bad" "2"
levels(x)[3:4] # should be no
#> [1] "3" "good"
图书馆(供猫用)
x[1]是是否否否否
#>级别:是否
#我不想重复是和否
级别(x)[1:2]#应为是
#>[1]坏的“2”
级别(x)[3:4]#应为否
#>[1]“3”良好
由(v0.3.0)创建于2020-10-03。您可以使用
library(forcats)
#By explicitly mentioning the levels to collapse
fct_collapse(x, yes = c('bad', '2'), no = c('3', 'good'))
#[1] yes yes yes no no no no no
#Levels: yes no
#By using levels
fct_collapse(x, yes = levels(x)[1:2], no = levels(x)[3:4])
#[1] yes yes yes no no no no no
#Levels: yes no