我使用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结构?