如果 != 从表中排除

发布于 2024-12-11 08:39:03 字数 272 浏览 0 评论 0原文

如果我使用 table() 我可以通过执行以下操作来排除元素:

b <- factor(rep(c("A","B","C"), 10))
table(b, exclude="B")

现在,如果我想排除除“B”之外的所有内容该怎么办?


我已经尝试过了 table(b, exlcude=!"B") 但它没有起作用。 table() 函数是否允许此功能?

If I'm using the table() I can exclude elements by doing:

b <- factor(rep(c("A","B","C"), 10))
table(b, exclude="B")

Now what if I want to exclude everything but "B"?

I have tried
table(b, exlcude=!"B") but it hasn't worked. does the table() function allow this functionality?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

别把无礼当个性 2024-12-18 08:39:03

您需要首先收集具有级别“B”的特定因子变量中的所有可能级别。可能有更简单的方法可以做到这一点,但假设发生所需排除的因素是“fac1”,那么也许是这样的:

with( datafrm, table(fac1, fac2, fac3, exclude=setdiff(levels(fac1), "B") ) )

我可能会用 subset 来减少“双重否定”:

with(subset( datafrm, fac1 == "B"), table(fac1, fac2, fac3) )

You would need to first gather all the possible levels in the particular factor variable(s) that has(have) a level "B". There are probably easier ways to do this, but assuming the factor in which the desired exclusion occurs is 'fac1' then perhaps something like:

with( datafrm, table(fac1, fac2, fac3, exclude=setdiff(levels(fac1), "B") ) )

I would probably have done it less "double negatively" with subset:

with(subset( datafrm, fac1 == "B"), table(fac1, fac2, fac3) )
如歌彻婉言 2024-12-18 08:39:03

您可以使用 setdiff:

table(iris$Species,exclude=setdiff(iris$Species,"virginica"))    
virginica 
       50 

当然,您也可以只对表对象进行子集化:

table(iris$Species)["virginica"]
virginica 
       50 

You can use setdiff:

table(iris$Species,exclude=setdiff(iris$Species,"virginica"))    
virginica 
       50 

Of course, you may as well just subset your table object:

table(iris$Species)["virginica"]
virginica 
       50 
蓝戈者 2024-12-18 08:39:03

就像简单一样,

table(b)['B']

但是为了计算一个值的出现次数,不需要使用 table。更简单的是这样的:

sum(b=='B')

As simple as

table(b)['B']

But for counting occurences of one value, there's no need to use table. Much simpler is this:

sum(b=='B')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文