使用嵌套循环自动创建统计分析公式

时间:2021-06-17 05:12:28

标签: r for-loop

假设我有一项纵向研究,该研究测量了 5 个不同时间点的生活质量 (QOL) 的各个方面。假设 QOL 有 4 个方面:(1) 社会、(2) 心理、(3) 身体和 (4) 情感。在整个研究中,每个方面总共测量 5 次。每个时间点 * facet 用作统计分析中的自变量。因此,要使用的公式是这样的:

DV ~ T1_QOL_social + T2_QOL_social + T3_QOL_social + T4_QOL_social + T5_QOL_social

其中 T 代表时间点,QOL 代表问卷名称,后缀代表任何给定的方面。

到目前为止我所做的是:

facet_names <- c("social", "psychological", "physical", "emotional")
container <- list()

for (i in facet_names) {
  for(j in 1:5) {
    container[[i]][[j]] <- paste0("T", j, "_QOL_", i)
  }
}

上面创建了一个包含元素(构面)的列表,其中包含可用作构建公式的输入的子元素(时间点 * 构面)。它看起来像这样(结果缩写):

$social
$social[[1]]
[1] "T1_QOL_social"

$social[[2]]
[1] "T2_QOL_social"

$social[[3]]
[1] "T3_QOL_social"

我需要折叠列表,以便列表中只有 4 个元素(方面),每个元素都包含公式的自变量部分。同时,我需要在子元素之间添加运算符(“+”),以使其显示为公式。

我搜索了 Stackoverflow,但找不到不仅涉及折叠列表,还涉及在它们之间粘贴字符串(例如“+”)的解决方案。我得到的最接近的是这里的这个问题,它合并跨元素的子元素,而不是跨给定元素的所有子元素:

Collapsing lists in R

我的理想输出如下:

$social[[1]]
[1] "T1_QOL_social + T2_QOL_social + T3_QOL_social + T4_QOL_social + T5_QOL_social"

$psychological[[1]]
[1] "T1_QOL_psychological + T2_QOL_psychological + T3_QOL_psychological + T4_QOL_psychological + T5_QOL_psychological"

$physical[[1]]
[1] "T1_QOL_physical + T2_QOL_physical + T3_QOL_physical + T4_QOL_physical + T5_QOL_physical"

$emotional[[1]]
[1] "T1_QOL_emotional + T2_QOL_emotional + T3_QOL_emotional + T4_QOL_emotional + T5_QOL_emotional"

谢谢!

2 个答案:

答案 0 :(得分:1)

尝试使用 lapply -

facet_names <- c("social", "psychological", "physical", "emotional")

lapply(facet_names, function(x) 
        paste0(sprintf("T%d_QOL_%s", 1:5, x), collapse = ' + '))

#[[1]]
#[1] "T1_QOL_social + T2_QOL_social + T3_QOL_social + T4_QOL_social + T5_QOL_social"

#[[2]]
#[1] "T1_QOL_psychological + T2_QOL_psychological + T3_QOL_psychological + T4_QOL_psychological + T5_QOL_psychological"

#[[3]]
#[1] "T1_QOL_physical + T2_QOL_physical + T3_QOL_physical + T4_QOL_physical + T5_QOL_physical"

#[[4]]
#[1] "T1_QOL_emotional + T2_QOL_emotional + T3_QOL_emotional + T4_QOL_emotional + T5_QOL_emotional"

答案 1 :(得分:0)

我们可以将 mapstringr 一起使用

library(purrr)
library(stringr)
facet_names <- c("social", "psychological", "physical", "emotional")
map(facet_names, ~  str_c('T', 1:5, '_QOL_', .x, collapse=" + "))