从 CI 输出制作 table

Making a table from CI output

我正在尝试从我的 CI 输出中制作 table,我没有在 R 中制作 table 的经验,非常感谢您的帮助。

CI <- data %>% group_by(group) %>% summarize(CI_z(column1, ci = 0.95)) 

我正在使用 CI_z 函数来获取我的置信区间信息。我有 4 个组,因为我的数据被分组到。我的输出如下所示:

group     Measurements   values
   <chr>     <chr>           <dbl>
 1 group1  sample_size     11   
 2 group1  Mean            39.3 
 3 group1  sd               6.35
 4 group1  Margin_Error     3.75
 5 group1  CI.lower.limit  35.5 
 6 group1  CI.Upper.limit  43.0 
 7 group2 sample_size      8   
 8 group2 Mean            35.2 
 9 group2 sd               4.79
10 group2 Margin_Error     3.32

等直到第 4 组结束

我想从此输出中提取数据,使 table 格式如下:

Group N Mean Lower Limit Upper limit
Group1 x x x x
Group2 x x x x
Group3 x x x x
Group4 x x x x

我知道如何使用: CI[,] 从列和行中获取特定数据,但我不知道如何使用它来制作我想要的 table。任何关于如何解决这个问题的建议都将不胜感激!

您可以执行以下操作,其中使用 dplyrtidyr,并假设数据为 df

library(dplyr)
library(tidyr)

df %>% 
  filter(!Measurements %in% c("sd", "Margin_Error")) %>% 
  pivot_wider(names_from=Measurements, values_from=values) %>% 
  rename_with(~c("Group", "N", "Mean", "Lower Limit", "Upper Limit"))

输出:

  Group      N  Mean `Lower Limit` `Upper Limit`
  <chr>  <dbl> <dbl>         <dbl>         <dbl>
1 group1    11  39.3          35.5          43  
2 group2     8  35.2          25.8          47.1

输入:

df = structure(list(group = c("group1", "group1", "group1", "group1", 
"group1", "group1", "group2", "group2", "group2", "group2", "group2", 
"group2"), Measurements = c("sample_size", "Mean", "sd", "Margin_Error", 
"CI.lower.limit", "CI.Upper.limit", "sample_size", "Mean", "sd", 
"Margin_Error", "CI.lower.limit", "CI.Upper.limit"), values = c(11, 
39.3, 6.35, 3.75, 35.5, 43, 8, 35.2, 4.79, 3.32, 25.8, 47.1)), row.names = c(NA, 
-12L), class = "data.frame")

这是一个可能的 data.table 选项(感谢@langtang 提供的数据):

library(data.table)

dt <- as.data.table(df)

results <- setnames(dt[,dcast(dt, group ~ Measurements, value.var = "values")][, !c("sd", "Margin_Error"), with=FALSE],
         c("Group", "Upper Limit", "Lower Limit", "Mean", "N"))

输出

    Group Upper Limit Lower Limit Mean  N
1: group1        43.0        35.5 39.3 11
2: group2        47.1        25.8 35.2  8