我想知道如何将下面的
TABLE
变成我的Desired_output
?
在我的
Desired_output
中,n_study
是 TABLE
中与 study
以外的列对应的值是 NOT 0 的行数。
例如,对于
TABLE
(, , treat_grp = conventional
) 中的第一个元素,n_study
的 baseline
是 1
,因为 baseline
只有 1 行包含非 0 元素,依此类推。
此外,在我的
Desired_output
中,sum
只是 TABLE
的每个元素的列总和。
我的
Desired_output
可以在R中使用吗?
(我尝试了
addmargins(TABLE) %>% as.data.frame.array()
但没有成功)
DATA <- structure(list(study = c(1, 1, 1, 1, 1, 1, 2, 2, 3, 4, 4, 4,
4, 5, 5), time = c("baseline", "posttest1", "posttest2", "baseline",
"posttest1", "posttest2", "posttest1", "posttest1", "posttest1",
"posttest1", "posttest1", "posttest1", "posttest1", "posttest1",
"posttest2"), treat_grp = c("conventional", "conventional", "conventional",
"conventional", "conventional", "conventional", "conventional",
"framework_notes", "conventional", "conventional", "conventional",
"conventional", "conventional", "vocabulary_notebook", "vocabulary_notebook"
)), row.names = c(NA, -15L), class = "data.frame")
TABLE <- table(DATA)
Desired_output <- read.table(header=T,text="
n_study time treat_grp sum
1 baseline conventional 2
4 posttest1 conventional 8
1 posttest2 conventional 2
0 baseline framework_notes 0
1 posttest1 framework_notes 1
0 posttest2 framework_notes 0
0 baseline vocabulary_notebook 0
1 posttest1 vocabulary_notebook 1
1 posttest2 vocabulary_notebook 1")
library(tidyverse)
DATA |>
count(study, time, treat_grp) |>
summarize(n_study = n(),
sum = sum(n),
.by = c(time, treat_grp)) |>
complete(time, treat_grp, fill = list(n_study = 0, sum = 0))
结果
# A tibble: 9 × 4
time treat_grp n_study sum
<chr> <chr> <int> <int>
1 baseline conventional 1 2
2 baseline framework_notes 0 0
3 baseline vocabulary_notebook 0 0
4 posttest1 conventional 4 8
5 posttest1 framework_notes 1 1
6 posttest1 vocabulary_notebook 1 1
7 posttest2 conventional 1 2
8 posttest2 framework_notes 0 0
9 posttest2 vocabulary_notebook 1 1