首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在R中创建比例表

如何在R中创建比例表
EN

Stack Overflow用户
提问于 2017-07-31 23:11:40
回答 1查看 992关注 0票数 0

如何创建比例表并将变量名称包含在表的第一列中?

下面是我的代码:

代码语言:javascript
运行
复制
time      <- c("Morning", "Evening" ,"Morning", "Morning", "Afternoon", "Evening", "Afternoon")
dollar    <- c("1-5", "6-10", "11-15", "1-5", "1-5", "6-10", "6-10")
with_kids <- c("no", "yes", "yes", "no", "no", "yes", "yes")
cluster   <- c(1,1,2,3,2,2,3)    
dat       <- data.frame(time, dollar, with_kids, cluster)

myList      <- lapply(dat[head(names(dat), -1)], table, dat$cluster)    
myList_Prop <- lapply(myList, prop.table, margin=2)

原问题:Table of categorical variables by a grouping variable in R

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-31 23:45:33

这样行得通吗?

代码语言:javascript
运行
复制
library(dplyr)
Map(function(x,n){x %>% round(2) %>% as.matrix %>% cbind(name=n,.)},myList_Prop,names(myList)) %>%
  do.call(rbind,.) %>%
  as.data.frame(stringsAsFactors=FALSE) %>%
  within({x<- rownames(.);name[duplicated(name)] <- ""}) %>%
  `[`(c(5,1,2,3,4)) %>%
  setNames(c('','',1,2,3)) %>%
  print(row.names = FALSE)

                       1    2   3
      time Afternoon   0 0.33 0.5
             Evening 0.5 0.33   0
             Morning 0.5 0.33 0.5
    dollar       1-5 0.5 0.33 0.5
               11-15   0 0.33   0
                6-10 0.5 0.33 0.5
 with_kids        no 0.5 0.33 0.5
                 yes 0.5 0.67 0.5
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45419496

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档