![](/img/trans.png)
[英]grouping table by multiple factors and spreading it from long format to wide - the data.table way in R
[英]way to create summary table in R with two grouping factors
我正在嘗試根據以下數據在 R 中創建一個包含兩個分組因素的匯總表
species plot type `mean(C)`
<fct> <fct> <fct> <dbl>
1 CA MI A -35.7
2 CA MI B -35.6
3 CA MI C -35.9
4 FO MI A -35.7
5 FO MI B -34.9
6 FO MI C -35.3
7 HE MI A -35.4
8 HE MI B -35.6
9 HE MI C -35.6
10 LA MI A -36.5
mean(C) 是我要顯示的響應變量,我希望根據類型和物種對其進行拆分; 即類型作為列和物種作為行
我嘗試使用的每個軟件包(xtable、stargazer、gtsummary)似乎都沒有能力做到這一點。 當然,我可以自己插電,但很高興知道是否有包裹。 有人有想法么?
非常感謝
這是使用 tidyr:: 包的一種解決方案。
library(tidyr)
# define your data as dataframe df
df <- data.frame("species" = c("CA","CA","CA","FO","FO", "FO", "HE", "HE", "HE", "LA"),
"plot" = c("MI"),
"type" = c("A", "B", "C", "A", "B", "C", "A", "B", "C", "A"),
"mean" = c(-35.7, -35.6, -35.9, -35.7, -34.9, -35.3, -35.4, -35.6, -35.6, -36.5))
# pivot df around 'type', using 'mean'
df %>%
pivot_wider(names_from = type, values_from = mean)
這將返回:
> df %>%
+ pivot_wider(names_from = type, values_from = mean)
# A tibble: 4 x 5
species plot A B C
<fct> <fct> <dbl> <dbl> <dbl>
1 CA MI -35.7 -35.6 -35.9
2 FO MI -35.7 -34.9 -35.3
3 HE MI -35.4 -35.6 -35.6
4 LA MI -36.5 NA NA
如果您只想要將類型變量值作為列呈現的數據框,那么您只是在 tidyverse 中尋找spread
函數。
library(tidyr)
df <- data.frame(species = c("CA", "CA", "CA", "FO", "FO", "FO", "HE", "HE", "HE", "LA"),
plot = "MI",
type = c("A", "B", "C", "A", "B", "C", "A", "B", "C", "A"),
mean_C = c(-35.7,-35.6,-35.9, -35.7,-34.9,-35.3, -35.4,-35.6, -35.6,-36.5))
new_df <- df %>%
spread(type, mean_C)
print(new_df)
您可以在 {gtsummary} 中使用tbl_strata()
添加任意數量的分層變量。 下面的例子!
library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.5.0'
tbl <-
trial %>%
mutate(grade = paste("Grade", grade)) %>%
tbl_strata(
strata = grade,
~ .x %>%
tbl_summary(
by = trt,
include = c(age, response),
missing = "no"
)
)
由reprex 包(v2.0.1) 於 2022 年 1 月 7 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.