R 获取其他向量的因子级别(和不存在的)
我有两个因素R 获取其他向量的因子级别(和不存在的),r,R,我有两个因素 foo_1 <- factor(c("a", "b", "c", "Other")) foo_2 <- factor(c("a", "b", "x")) 背景 我正在构建randomForest()s,预测数据中可能存在开发数据中不存在的级别,并且预测是不可能的,这非常烦人。(foo_1是来自开发数据的向量,foo_2是来自预测
foo_1 <- factor(c("a", "b", "c", "Other"))
foo_2 <- factor(c("a", "b", "x"))
背景 我正在构建
randomForest()
s,预测数据中可能存在开发数据中不存在的级别,并且预测是不可能的,这非常烦人。(foo_1
是来自开发数据的向量,foo_2
是来自预测数据的向量。)我敢打赌,其他人以前肯定也有过同样的问题,答案应该在那里,但我找不到
我希望使用forcats
包来解决问题,但也非常欢迎使用其他方法
提前谢谢。下面的内容怎么样
> replace(u <- foo_1[match(levels(foo_2),levels(foo_1))],is.na(u),"Other")
[1] a b Other
Levels: a b c Other
>替换(u下面的内容怎么样
> replace(u <- foo_1[match(levels(foo_2),levels(foo_1))],is.na(u),"Other")
[1] a b Other
Levels: a b c Other
>替换(u一个简单的方法是:
foo_3 <- factor(foo_2, levels = levels(foo_1))
foo_3[is.na(foo_3)] <- 'Other'
foo_3
#[1] a b Other
#Levels: a b c Other
一个简单的方法是:
foo_3 <- factor(foo_2, levels = levels(foo_1))
foo_3[is.na(foo_3)] <- 'Other'
foo_3
#[1] a b Other
#Levels: a b c Other
扩展Ronaks答案,并使用magrittr
管道(%%>%%
)使其更加优雅:
扩展Ronaks答案,并使用magrittr
管道(%%>%%
)使其更加优雅:
谢谢。forcats
解决方案不正确。谢谢。forcats
解决方案不正确。
library (forcats)
foo_2 %>% fct_expand(levels(foo_1)) %>% fct_other(levels(foo_1))
[1] a b Other
Levels: a b c Other