2017-06-01 109 views
0

我正在将统计分析脚本从SPSS转换为R,当涉及到输出表格时虽然我一直在提出问题。 我最近开始使用tidyverse软件包,所以理想情况下希望找到一个适用于该软件的解决方案,但更一般地说,如果存在这样的事情,我希望指向R的一些深度表培训。R tidyverse表格演示文稿

反正...这里是表格的布局我希望复制:

enter image description here

本质上讲,它是一个频率

下面是一些样本数据的一些脚本:

i <- c(201:301) 
ID <- sample(i, 200, replace=TRUE) 
i <- 1:2 
Category1 <- sample(i, 200, replace=TRUE) 
Category2 <- sample(i, 200, replace=TRUE) 
Category3 <- sample(i, 200, replace=TRUE) 
df <- data.frame(ID, Category1, Category2, Category3) 

现在我试过了:

IDTab <- df %>% 
      mutate(ID = as.character(ID)) %>% 
      group_by(ID) %>% 
      summarise(C1_1 = NROW(Category1[which(Category1 == 1)]) 
        ,C1_2 = NROW(Category1[which(Category1 == 2)]) 
        ,C1_T = NROW(Category1) 
        ,C2_1 = NROW(Category2[which(Category2 == 1)]) 
        ,C2_2 = NROW(Category2[which(Category2 == 2)]) 
        ,C2_T = NROW(Category2) 
        ,C3_1 = NROW(Category3[which(Category3 == 1)]) 
        ,C3_2 = NROW(Category3[which(Category3 == 2)]) 
        ,C3_T = NROW(Category3)) 

然而,这看起来很荒谬的手动,并会显着增加工作量,因为包括更多的变量/级别。更不用说,我已经创建了我想要的表的数据框,而不是数据框中的表,并且所有的分类都来自命名约定,而不是任何实际的数据结构。

正如我所说...硬核的建议R表培训,欢迎。

回答

3

如果你想漂亮的表格,看看在knitr::kablepander::panderztable::ztablextable::xtable喜欢(在增加通用性的粗糙顺序)。

下面的数据处理示例不会为您提供您正在查找的嵌套表格格式,但它应该比您当前的代码缩放得更好,并且会为您提供所需的数据。


# Make dataframe 
set.seed(1234) 
i <- c(201:301) 
ID <- sample(i, 200, replace=TRUE) 
i <- 1:2 
Category1 <- sample(i, 200, replace=TRUE) 
Category2 <- sample(i, 200, replace=TRUE) 
Category3 <- sample(i, 200, replace=TRUE) 
df <- data.frame(ID, Category1, Category2, Category3) 

# Load packages 
library(dplyr) 
library(tidyr) 

# Get the count by 'Level' (1 or 2) per 'Category' (1, 2 or 3) for each ID 
df2 <- df %>% 
    # Gather the 'Category' columns 
    gather(key = Category, 
      value = Level, 
      -ID) %>% 
    # Convert all to character 
    mutate_each(funs(as.character)) %>% 
    # Group by and then count 
    group_by(ID, Category, Level) %>% 
    summarise(Count = n()) 

# Get the total count per 'Category' (1, 2 or 3) for each ID 
df3 <- df2 %>% 
    # Group by and then count 
    group_by(ID, Category) %>% 
    summarise(Count = sum(Count)) %>% 
    # Add a label column 
    mutate(Level = 'total') %>% 
    # reorder columns to match df2 
    select(ID, Category, Level, Count) 

# Finishing steps 
df4 <- df2 %>% 
    # Bind df3 to df2 by row 
    rbind(df3) %>% 
    # Spread out 'Level' into columns 
    spread(key = Level, 
      value = Count) 

# Tabulate 
knitr::kable(head(df4), format = 'markdown') 

|ID |Category | 1| 2| total| 
|:---|:---------|--:|--:|-----:| 
|201 |Category1 | 1| NA|  1| 
|201 |Category2 | NA| 1|  1| 
|201 |Category3 | NA| 1|  1| 
|202 |Category1 | 2| NA|  2| 
|202 |Category2 | 1| 1|  2| 
|202 |Category3 | 2| NA|  2| 

(感谢珍妮布莱恩为reprex