如何检查因子变量是否只有我想要的水平?

Sma*_*ess 0 r levels factors

验证因子变量的最简单方法是什么?

# I want to make sure a factor variable has 'FP', 'TP' but nothing else

a <- factor(c('TP','TP','FP')) # Return TRUE
b <- factor(c('TP')) # Return TRUE
c <- factor(c('TP', '1234')) # Return FALSE
Run Code Online (Sandbox Code Playgroud)

Ron*_*hah 5

我们可以使用all%in%

all(levels(a) %in% c("FP", "TP"))
#[1] TRUE
all(levels(b) %in% c("FP", "TP"))
#[1] TRUE
all(levels(c) %in% c("FP", "TP"))
#[1] FALSE
Run Code Online (Sandbox Code Playgroud)

只是为了避免重复代码或者如果有更多级别我们需要检查

checkFactor <- c("FP", "TP")
all(levels(a) %in% checkFactor)
#[1] TRUE
all(levels(b) %in% checkFactor)
#[1] TRUE
all(levels(c) %in% checkFactor)
#[1] FALSE
Run Code Online (Sandbox Code Playgroud)