你如何强制在R中的表中包含一个级别?(How can you force inclusion of a level in a table in R?)

编程入门 行业动态 更新时间:2024-10-18 08:37:13
你如何强制在R中的表中包含一个级别?(How can you force inclusion of a level in a table in R?)

有没有办法迫使R的table函数包含行或列,即使它们从未出现在数据中? 例如,

data.1 <- c(1, 2, 1, 2, 1, 2, 4) data.2 <- c(1, 4, 3, 3, 3, 1, 1) table(data.1, data.2)

回报

data.2 data.1 1 3 4 1 1 2 0 2 1 1 1 4 1 0 0

行中缺少3个,列中缺少2个,因为它们没有出现在数据中。

是否有一种简单的方法可以强制将其他行和列插入正确的位置,而是返回以下内容?

data.2 data.1 1 2 3 4 1 1 0 2 0 2 1 0 1 1 3 0 0 0 0 4 1 0 0 0

Is there a way to force R's table function to include rows or columns even when they never occur in the data? For example,

data.1 <- c(1, 2, 1, 2, 1, 2, 4) data.2 <- c(1, 4, 3, 3, 3, 1, 1) table(data.1, data.2)

returns

data.2 data.1 1 3 4 1 1 2 0 2 1 1 1 4 1 0 0

where there's a missing 3 in the rows and a missing 2 in the columns, because they don't appear in the data.

Is there a simple way to force additional rows and columns of zeros to be inserted in the correct place, and instead return the following?

data.2 data.1 1 2 3 4 1 1 0 2 0 2 1 0 1 1 3 0 0 0 0 4 1 0 0 0

最满意答案

您需要将向量转换为factor s,每个向量都包含要包含在输出中的所有levels 。

levs <- sort(union(data.1, data.2)) table(factor(data.1, levs), factor(data.2, levs)) # # 1 2 3 4 # 1 1 0 2 0 # 2 1 0 1 1 # 3 0 0 0 0 # 4 1 0 0 0

You need to convert your vectors to factors, with each vector having all the levels you want to include in your output.

levs <- sort(union(data.1, data.2)) table(factor(data.1, levs), factor(data.2, levs)) # # 1 2 3 4 # 1 1 0 2 0 # 2 1 0 1 1 # 3 0 0 0 0 # 4 1 0 0 0

更多推荐

本文发布于:2023-08-01 21:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1365795.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:级别   force   inclusion   level   table

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!