我有一个具有多个级别的因子,我试图获得因子级别包含给定字符串的级别数。
考虑到这个因素:
exdata <- factor(c("Test1","Test2","Sample1","Sample2","Test1","Test2","Sample3"))
我想在exdata中找到包含&#34; Sample&#34;的数量级别。或&#34;测试。&#34;
到目前为止,我的解决方案是使用nlevels
,droplevels
和grep
:
nlevels(droplevels(exdata[grep("Test",exdata)]))
# Correct/intended answer is 2
nlevels(droplevels(exdata[grep("Sample",exdata)]))
# Correct/intended answer is 3
有更简洁的方法吗?