代码之家  ›  专栏  ›  技术社区  ›  Steve

R中包含百分比的分类变量表

  •  0
  • Steve  · 技术社区  · 7 年前

    我有一系列分类变量,它们有响应选项(有利、不利、中性)。

    我想在R中创建一个表,该表将给出所有10个变量的行列表(每行一个变量),列中的百分比响应为“有利、不利、中性”。这在R中可能吗?理想情况下,我还希望能够通过另一个分类变量将其分组(例如,比较男性与女性对问题的不同反应)。

    2 回复  |  直到 7 年前
        1
  •  2
  •   lefft    7 年前

    如果您提供实际数据的样本,您会得到更好的答案(请参阅 this post ). 也就是说,这里有一个使用 dplyr:: (和 reshape2::melt ).

    # function to create a column of fake data 
    make_var <- function(n=100) sample(c("good","bad","ugly"), size=n, replace=TRUE)
    
    # put ten of them together 
    dat <- as.data.frame(replicate(10, make_var()), stringsAsFactors=FALSE) 
    
    library("dplyr")
    
    # then reshape to long format, group, and summarize -- 
    dat %>% reshape2::melt(NULL) %>% group_by(variable) %>% summarize(
        good_pct = (sum(value=="good") / length(value)) * 100, 
        bad_pct = (sum(value=="bad") / length(value)) * 100, 
        ugly_pct = (sum(value=="ugly") / length(value)) * 100
    )
    

    请注意,要按另一列(例如性别)分组,您可以说 group_by(variable, sex) 在总结之前(只要 sex 是一列数据,但在这个构造的示例中并非如此)。

        2
  •  -1
  •   Marius    7 年前

    适应 lefft 的示例,但尝试在 dplyr :

    dat %>% 
        gather(variable, value) %>%
        group_by(variable) %>%
        count(value) %>%
        mutate(pct = n / sum(n) * 100) %>%
        select(-n) %>%
        spread(value, pct)