> t <- read.csv("data.csv", sep=';')
> t
sex pacemaker smoker
1 female no never
2 female no never
3 male no never
4 male no former
5 male yes former
6 male yes former
7 female yes current
8 female yes former
9 female no current
> xtabs(~smoker+sex, data=t)
sex
smoker female male
current 2 0
former 1 3
never 2 1
> xtabs(~smoker+pacemaker, data=t)
pacemaker
smoker no yes
current 1 1
former 1 3
never 3 0
如何在R?
中组合两个二维交叉表期望的输出:
| sex | pacemaker
smoker | female male | no yes
current | 2 0 | 1 1
former | 1 3 | 1 3
never | 2 1 | 3 0
答案 0 :(得分:2)
我已将您的data.frame重命名为df。此代码应该适合您。
cbind(xtabs(~smoker+sex, data=df), xtabs(~smoker+pacemaker, data=df))
female male no yes
current 2 0 1 1
former 1 3 1 3
never 2 1 3 0
您可能想要重命名起搏器列标题。
colnames(XTab)[3:4] = c("Pacemaker_no", "Pacemaker_yes")
XTab
female male Pacemaker_no Pacemaker_yes
current 2 0 1 1
former 1 3 1 3
never 2 1 3 0