重复两个字符串,每个字符串重复固定次数

repeat two strings of characters, each for a fixed number of times

我有 200 次试验和 2 个条件。我需要创建一个字符串序列,其中每个条件下的每个试验按以下顺序重复 4 次:

 [1] "TRIAL_1_condition_1" [2] "TRIAL_1_condition_1" [3] "TRIAL_1_condition_1" [4] "TRIAL_1_condition_1"
 [5] "TRIAL_1_condition_2" [6] "TRIAL_1_condition_2" [7] "TRIAL_1_condition_2" [8] "TRIAL_1_condition_2"
 [9] "TRIAL_2_condition_1" [10] "TRIAL_2_condition_1" [11] "TRIAL_2_condition_1" [12] "TRIAL_2_condition_1"
 [13] "TRIAL_2_condition_2" [14] "TRIAL_2_condition_2" [15] "TRIAL_2_condition_2" [16] "TRIAL_2_condition_2"

所以,我最终应该得到 1152 行。 我试过这段代码:

 x <- rep(1:200, each=4)
 x

 VarNames <-c(sprintf("TRIAL_%d_condition_1", x),sprintf("TRIAL_%d_condition_2", x))
 VarNames

但是,通过这种方式,我首先获得与条件 1 的所有试验相关的所有字符串,然后获得条件 2 的所有试验。 我不知道如何让 R 以正确的顺序排列它们(即在条件 1 中试验 1 4 次,然后在条件 2 中试验 1 4 次,在条件 1 中试验 2 4 次,然后试验 2条件 2 中的 4 次,依此类推)。如果有人有建议,谢谢。

原题:

paste("TRIAL",sort(rep(1:200, 8)), "condition", rep(sort(rep(1:2,4)), 200), sep = "_")

对于评论中的问题:

解决方案1:

varnames <- paste("TRIAL",sort(rep(1:200, 8)), "condition", rep(sort(rep(1:2,4)), 200), sep = "_")
library(stringr)
varnames2 <- str_replace(varnames, "condition_1", "animal")
varnames2 <- str_replace(varnames2, "condition_2", "plant")

解决方案2:

varnames3 <- paste("TRIAL", sort(rep(1:200, 8)), rep(sort(rep(c("animal", "plant"), 4)), 200), sep = "_")