gpt4 book ai didi

Extracting an xtabs subarray from an array given condition in R(从R中给定条件的数组中提取xTabs子数组)

转载 作者:bug小助手 更新时间:2023-10-25 12:04:54 25 4
gpt4 key购买 nike



There is a 2-way table which is an array from xtabs(), like this:

有一个双向表,它是xtabs()中的一个数组,像这样:


    A  B
12 0 0
20 1 0
41 22 16
49 4 8
50 0 1
56 3 2
57 4 2
59 1 0
63 0 3
64 2 1
65 0 0
68 0 1
71 2 7
72 2 1
73 9 7
78 0 1

How can one extract a subtable such that each cell must be 2 or greater? The resulting table would look like this:

如何提取一个子表,使每个单元格都必须大于或等于2?生成的表格将如下所示:


    A  B
41 22 16
49 4 8
56 3 2
57 4 2
71 2 7
73 9 7

更多回答
优秀答案推荐


Filter it like you would any other matrix.

像过滤其他矩阵一样对其进行过滤。


tab[rowSums(tab < 2) == 0,]
# A B
# 41 22 16
# 49 4 8
# 56 3 2
# 57 4 2
# 71 2 7
# 73 9 7



Data

数据


tab <- structure(c(0L, 1L, 22L, 4L, 0L, 3L, 4L, 1L, 0L, 2L, 0L, 0L, 2L, 2L, 9L, 0L, 0L, 0L, 16L, 8L, 1L, 2L, 2L, 0L, 3L, 1L, 0L, 1L, 7L, 1L, 7L, 1L), dim = c(16L, 2L), dimnames = list(c("12", "20", "41", "49", "50", "56", "57", "59", "63", "64", "65", "68", "71", "72", "73", "78"), c("A", "B")), class = c("xtabs", "table"))

更多回答

Thanks r2evans! I had a similar solution but this works only for r x 2 tables, right? That I did not like. So, could the general solution be tab[rowSums(tab < dim(tab)[2]) == 0,]?

谢谢r2evans!我有一个类似的解决方案,但这只适用于rx2表,对吗?这是我不喜欢的。那么,一般的解决方案是否可以是TAB[rowSums(TAB

That logic is different than in your question. You said "each cell must be 2 or greater", which is where the 2 in my answer comes from. In my (limited) understand, that 2 is not the same as ncol(tab) (which is also 2, but only coincidentally). If you have 17 columns and you want rows where all cells in that row are 2 or greater, then my code (tab[rowSums(tab < 2) == 0,]) remains unchanged.

这种逻辑与你问题中的不同。你说“每个单元格必须是2或更大”,这就是我答案中2的来源。在我(有限的)理解中,2不等同于nol(制表符)(也是2,但只是巧合)。如果您有17列,并且希望该行中的所有单元格都是2或更大的行,那么我的代码(tab[rowSums(tab<2)==0,])保持不变。

Oh, I see now... rowSums() misled me. It automatically converts booleans to integers, and only if both are FALSE (0) than the condition hold. Sorry. Great stuff. Thanks r2evans!

哦,我现在明白了.RowSums()误导了我。它自动将布尔值转换为整数,并且仅当两者都为假(0)时才会满足条件。抱歉的。很棒的东西。谢谢r2evans!

yes, R silently casts ... so sum(c(T,F,T)) sums to 2. Glad it helps!

是的,R默默地投下..。所以sum(c(T,F,T))等于2。很高兴它有帮助!

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com