我正在尝试以ftable()
格式在R中创建3向/ 3维列联表以进行测试。不幸的是,我所见过的所有有关如何创建此示例的示例都是从尚未进行计数的大型数据集中获取数据的。我已经有了计数的摘要。 手动可以在R中输入我的数据吗?
例如,我通常用于创建二维意外事件的方法,例如2x3用于手动输入矩阵,例如matrix(c(10, 20, 30, 40, 50, 60), nrow=3, ncol=2)
我想找到一种类似的方法来输入3维表的数据。
我有三个变量-种族,身材,饮食。我的数据看起来像这样:
MEDITERRANEAN DIET
Race
White Black
Slim 35 55
Normal 75 65
Obese 100 80
AMERICAN DIET
Race
White Black
Slim 12 10
Normal 50 70
Obese 255 157
并且我正在寻找ftable()
格式的输出示例是:
DIET American Mediterranean
RACE BUILD
White Slim 12 35
Normal 50 75
Obese 255 100
Black Slim 10 55
Normal 70 65
Obese 157 80
谢谢!
在将数据作为矢量输入后,可以使用dim
设置矩阵的尺寸,然后单击aperm
重新排列尺寸。
mat <- c(12,50,255,10,70,157, 35, 75, 100, 55, 65, 80)
dim(mat) <- c(3,2,2)
dimnames(mat) <- list(Weight=c("Slim","Normal","Obese"),
Race=c("White","Black"),
Diet=c("American","Mediterranean"))
, , Diet = American
Race
Weight White Black
Slim 35 55
Normal 75 65
Obese 100 80
, , Diet = Mediterranean
Race
Weight White Black
Slim 12 10
Normal 50 70
Obese 255 157
ftable
做您想要的,但是由于尺寸问题,输出的方向不理想。
ftable(mat)
因此您可以使用aperm
重新排列尺寸,切换行和列:
mat2 <- aperm(mat, c(2,1,3))
ftable(mat2)
Diet American Mediterranean
Race Weight
White Slim 35 12
Normal 75 50
Obese 100 255
Black Slim 55 10
Normal 65 70
Obese 80 157
当然,您总是可以首先以正确的顺序输入数据,然后不需要aperm
命令。