对于论文,我需要结果的形式是平均值±SD。有4种情况:
我已经制作了一个解决前三种情况的功能,但我不能做到最后一次。以下是一个例子:
df <- data.frame(treatment = c(rep(c("Stimulation", "Control"), 8)),
group = c(rep(c("A", "B"), 4),
rep(c("B", "A"), 4)),
value = rnorm(16, mean = 150, sd = 20))
df$units <- ifelse(df$group == "A", "ml", "min")
strg <- function(df, vec, u){
l <- lapply(levels(vec), function(x){
list(
Stimulation = paste(
myround(mean(df$value[vec==x & df$treatment=="Stimulation"]), 2), "±",
myround(sd(df$value[vec==x & df$treatment=="Stimulation"]), 2)
),
Control = paste(
myround(mean(df$value[vec==x & df$treatment=="Control"]), 2), "±",
myround(sd(df$value[vec==x & df$treatment=="Control"]), 2)
))
})
set_names(l, levels(vec))
}
a <- strg(df, vec = df$group, u = df$units)
add_unit <- function(list, vec, u){
z <- lapply(list, function(x){
list(
Stimulation = paste(x$Stimulation, u[vec==x]),
Control = paste(x$Control, u[vec==x]))
})
}
b <- add_unit(a, vec = df$group, u = df$units)
问题似乎是u [vec == x]位。最终输出需要具有平均值±标准差和匹配单位。如何在匹配分组因子的同时添加单位?
编辑: 当分组存在且我们想要添加单位
时,最终结果应如下所示[[1]]
[[1]]$Stimulation
[1] "154.37 ± 15.9 ml"
[[1]]$Control
[1] "153.32 ± 15.79 ml"
[[2]]
[[2]]$Stimulation
[1] "152.24 ± 17.78 min"
[[2]]$Control
[1] "138.48 ± 31.96 min"
如果不需要单位,它应该是这样的:
[[1]]
[[1]]$Stimulation
[1] "154.37 ± 15.9"
[[1]]$Control
[1] "153.32 ± 15.79"
[[2]]
[[2]]$Stimulation
[1] "152.24 ± 17.78"
[[2]]$Control
[1] "138.48 ± 31.96"
(基本上我试图做的是在“a”中创建上面的字符串然后将单元添加到结尾,如果需要,导致“b”)
答案 0 :(得分:1)
整个事情在tidyverse中重写,其中(在我看来;)代码的意图更清晰易懂:
library(tidyverse)
df %>%
group_by(group, treatment) %>%
summarise(
mean = mean(value),
sd = sd(value)) %>%
mutate(
msd = paste(round(mean, 2), "±", round(sd, 2)),
unit = group %>% recode(A = "ml", B = "min", .default = ""),
result = if_else(unit == "",
msd,
paste(msd, unit)))
计算/聚合与格式分开,单位取决于group
变量。目前还不完全清楚你想要达到的目标(问题中交错的案例太多),但你可以分别用msd
和result
列中的/ witout单位得到结果。