为具有两个以上组的离散数据计算百分比 table 的简单方法?
Simple way to make a percentage table for discrete data with more than two groups?
有什么简单的方法可以在 R 中为离散的 table 制作这样的 table :
1. table 中的值是每一行的百分比。
2.分成两组以上。
比如数据是
Success Gender Level
1 M High
1 M Low
1 F Med
0 M Low
0 M Med
0 F High
想要的table看起来像这样
Success=1 Success=0
Level=High Level=Med Level=Low Level=High Level=Med Level=Low
Gender=F 0 0.5 0 0.5 0 0
Gender=M 0.25 0 0.25 0 0.25 0.25
您可以将 ftable()
与 prop.table()
一起使用。将 row.vars
指定为第二列将生成看起来像您想要的 table 的 table(顺序略有不同)。
prop.table(ftable(df, row.vars = 2), margin = 1)
# Success 0 1
# Level High Low Med High Low Med
# Gender
# F 0.50 0.00 0.00 0.00 0.00 0.50
# M 0.00 0.25 0.25 0.25 0.25 0.00
对于完全需要的 table,您可以重构列以更改级别的顺序。
df2 <- transform(
df,
Level = factor(Level, levels = c("High", "Med", "Low")),
Success = factor(Success, levels = 1:0)
)
prop.table(ftable(df2, row.vars = 2), margin = 1)
# Success 1 0
# Level High Med Low High Med Low
# Gender
# F 0.00 0.50 0.00 0.50 0.00 0.00
# M 0.25 0.00 0.25 0.00 0.25 0.25
数据:
df <- structure(list(Success = c(1L, 1L, 1L, 0L, 0L, 0L), Gender = structure(c(2L,
2L, 1L, 2L, 2L, 1L), .Label = c("F", "M"), class = "factor"),
Level = structure(c(1L, 2L, 3L, 2L, 3L, 1L), .Label = c("High",
"Low", "Med"), class = "factor")), .Names = c("Success",
"Gender", "Level"), class = "data.frame", row.names = c(NA, -6L
))
有什么简单的方法可以在 R 中为离散的 table 制作这样的 table : 1. table 中的值是每一行的百分比。 2.分成两组以上。 比如数据是
Success Gender Level
1 M High
1 M Low
1 F Med
0 M Low
0 M Med
0 F High
想要的table看起来像这样
Success=1 Success=0
Level=High Level=Med Level=Low Level=High Level=Med Level=Low
Gender=F 0 0.5 0 0.5 0 0
Gender=M 0.25 0 0.25 0 0.25 0.25
您可以将 ftable()
与 prop.table()
一起使用。将 row.vars
指定为第二列将生成看起来像您想要的 table 的 table(顺序略有不同)。
prop.table(ftable(df, row.vars = 2), margin = 1)
# Success 0 1
# Level High Low Med High Low Med
# Gender
# F 0.50 0.00 0.00 0.00 0.00 0.50
# M 0.00 0.25 0.25 0.25 0.25 0.00
对于完全需要的 table,您可以重构列以更改级别的顺序。
df2 <- transform(
df,
Level = factor(Level, levels = c("High", "Med", "Low")),
Success = factor(Success, levels = 1:0)
)
prop.table(ftable(df2, row.vars = 2), margin = 1)
# Success 1 0
# Level High Med Low High Med Low
# Gender
# F 0.00 0.50 0.00 0.50 0.00 0.00
# M 0.25 0.00 0.25 0.00 0.25 0.25
数据:
df <- structure(list(Success = c(1L, 1L, 1L, 0L, 0L, 0L), Gender = structure(c(2L,
2L, 1L, 2L, 2L, 1L), .Label = c("F", "M"), class = "factor"),
Level = structure(c(1L, 2L, 3L, 2L, 3L, 1L), .Label = c("High",
"Low", "Med"), class = "factor")), .Names = c("Success",
"Gender", "Level"), class = "data.frame", row.names = c(NA, -6L
))