r - 如何在不丢失行名和列名的情况下对 R 中的平面列联表进行子集化?

我正在使用 ftable 创建一个平面列联表。但是,当我对列联表进行子集化时,R 会删除行名和列名。有没有办法对表进行子集化,以使行名和列名保留在子集表中?这是一个例子:

# Create fake data
Group1 = sample(LETTERS[1:3], 20, replace=TRUE)
Group2 = sample(letters[1:3], 20, replace=TRUE)
Year = sample(c("2010","2011","2012"), 20, replace=TRUE)
df1 = data.frame(Group1, Group2, Year)

# Create flat contingency table with column margin
table1 = ftable(addmargins(table(df1$Group1, df1$Group2, df1$Year), margin=3))

# Select rows with sum greater than 2
table2 = table1[table1[ ,4] > 2, ]

> table1
     2010 2011 2012 Sum

A a     0    1    2   3
  b     2    1    0   3
  c     0    0    0   0
B a     0    1    1   2
  b     2    0    0   2
  c     1    0    1   2
C a     0    1    0   1
  b     1    0    2   3
  c     3    0    1   4

> table2
     [,1] [,2] [,3] [,4]
[1,]    0    1    2    3
[2,]    2    1    0    3
[3,]    1    0    2    3
[4,]    3    0    1    4

请注意 R 如何将子集表转换为矩阵,去除列名和两个级别的行名。如何将 ftable 结构保留在子集表中?

最佳答案

考虑使用频率的 data.frame。这是一个更好的数据结构,特别是如果你要过滤它。这是一种使用 reshape 包构建的方法。

# cast the data into a data.frame
library(reshape)
df1$Freq <- 1
df2 <- cast(df1, Group1 + Group2 ~ Year, fun = sum, value = "Freq")
df2
#   Group1 Group2 2010 2011 2012
# 1      A      a    0    0    1
# 2      A      b    1    1    3
# 3      A      c    0    0    1
# 4      B      a    1    2    0
# 5      B      b    1    1    0
# 6      B      c    0    0    1
# 7      C      a    2    0    1
# 8      C      b    2    0    0
# 9      C      c    0    0    2

# add a column for the `Sum` of frequencies over the years
df2 <- within(df2, Sum <- `2010` + `2011` + `2012`)
df2
#   Group1 Group2 2010 2011 2012 Sum
# 1      A      a    0    0    1   1
# 2      A      b    1    1    3   5
# 3      A      c    0    0    1   1
# 4      B      a    1    2    0   3
# 5      B      b    1    1    0   2
# 6      B      c    0    0    1   1
# 7      C      a    2    0    1   3
# 8      C      b    2    0    0   2
# 9      C      c    0    0    2   2

df2[df2$Sum > 2, ]
#   Group1 Group2 2010 2011 2012 Sum
# 2      A      b    1    1    3   5
# 4      B      a    1    2    0   3
# 7      C      a    2    0    1   3

https://stackoverflow.com/questions/9895368/

相关文章:

html - 不熟悉的 Javascript 语法/hack

java - java.util.Formattable 上的示例是否不正确?

formatting - 使用 LaTeX Beamer 将引文文本放在同一张幻灯片上

python - Gtk3 TextBuffer.serialize() 返回带有格式标签的文本,即

formatting - 引用 YAML(对于 Travis CI)

eclipse - 如何配置 Eclipse 格式化程序在字段声明之间不插入空行?

c - 如何将 "unbreak"C 代码与 "Artistic Style"

javascript - Bootstrap datepicker 显示的日期格式与值的格式不同

.net - 为什么 DateTime.ToShortTimeString() 不尊重 "Regio

.net - 如何在格式字符串中指定自定义千位分隔符