使用子集在R中创建交叉表

时间:2017-03-19 13:12:13

标签: r

我有这张桌子:

Table smoker

现在我想为年龄较小的年轻人创建一个交叉表,所以它看起来像这样:

/ alive / dead

1/372/46

0/393/25

我想使用子集从原始表中获取正确的数据,但我真的不知道从哪里开始,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

尝试:

SmokersAlive <- subset(df, Smoker == 1)            #table showing only the smokers
SmokersAlive <- sum(subset(df, Smoker == 1)$Alive) #sum of col. "Alive" from table above

这里是您需要的代码:

SmokersAlive <- sum(subset(df, Smoker == 1)$Dead)

SmokersDead     <- 1 #sum(subset....) should stand here
NonSmokersAlive <- 1 #...
NonSmokersDead  <- 1

Overview <- data.frame(matrix(c(SmokersAlive, SmokersDead, NonSmokersAlive, NonSmokersDead), ncol = 2, byrow = TRUE))

colnames(Overview) <- c("alive","dead")
rownames(Overview) <- c("0","1")

Overview