【问题标题】:How to apply proptable() to all the factor variables in R如何将 proptable() 应用于 R 中的所有因子变量
【发布时间】:2021-06-20 10:03:16
【问题描述】:

我有一个包含许多不同级别的因子变量的数据集。如何有效地为每个因子变量打印出proptable()。预期的答案是数据框或表格。非常感谢。

df <- mtcars[, c("am", "gear")]
df$am <- factor(df$am); df$gear <- factor(df$gear)


prop.table(table(df$am))
prop.table(table(df$gear))

【问题讨论】:

  • 你不想prop.table(table(df))?还是margin.table(table(df), margin = 1:2)

标签: r lapply data-manipulation


【解决方案1】:

也许是 sapply?

sapply(df, function(x) if("factor" %in% class(x)) {prop.table(table(x))})

例如当 prop.table(table(df)) 抛出错误时:

library(palmerpenguins)

prop.table(table(penguins))
#Error in table(penguins) : attempt to make a table with >= 2^31 elements

sapply(penguins, function(x) if("factor" %in% class(x)) {prop.table(table(x))})
#$species
#x
#   Adelie Chinstrap    Gentoo 
#0.4418605 0.1976744 0.3604651 

#$island
#x
#   Biscoe     Dream Torgersen 
#0.4883721 0.3604651 0.1511628 

#$bill_length_mm
#NULL

#$bill_depth_mm
#NULL

#$flipper_length_mm
#NULL

#$body_mass_g
#NULL

#$sex
#x
#   female      male 
#0.4954955 0.5045045 

#$year
#NULL

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多