我有一个如下所示的数据源:
pirate_size pirate_age victim_size
large adult large
large adult large
large immature small
small immature small
small immature small我想在R中创建一个列联表,其中包含除以总行数的值(在本例中,总行数为5)。使用下面的代码,我得到了一个正常的列联表:
table1 <-(data$pirate_age,data$pirate_size)但我希望输出是:
Adult Immature
Large 2/5 1/5
Small 0 2/5发布于 2019-10-02 21:37:58
使用table后除以行数
table(df$pirate_size, df$pirate_age)/nrow(df)
# adult immature
# large 0.4 0.2
# small 0.0 0.4data
df <- structure(list(pirate_size = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("large",
"small"), class = "factor"), pirate_age = structure(c(1L, 1L,
2L, 2L, 2L), .Label = c("adult", "immature"), class = "factor"),
victim_size = structure(c(1L, 1L, 2L, 2L, 2L), .Label = c("large",
"small"), class = "factor")), class = "data.frame", row.names = c(NA, -5L))发布于 2019-10-02 21:40:36
也可以使用prop.table()并重新格式化为%:
prop.table(table(df$pirate_size, df$pirate_age))*100
adult immature
large 40 20
small 0 40发布于 2019-10-02 21:43:58
一种选择是使用针对fun.aggeregate的自定义函数将dcast转换为long。注意:这将给出一个数据框而不是一个"table“类的对象。
library(data.table)
dcast(df, pirate_size ~ pirate_age, value.var = 'pirate_age',
fun.aggregate = function(x) length(x)/nrow(df))
# pirate_size adult immature
# 1 large 0.4 0.2
# 2 small 0.0 0.4https://stackoverflow.com/questions/58202569
复制相似问题