dede dede - 1 month ago 12
R Question

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

I have 200 trials and 2 conditions. I need to create a sequence of strings, where each trial in each condition is repeated 4 times in the following order:

[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"


So, I should end up with 1152 rows.
I have tried this code:

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

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


However, in this way I obtain first all the strings associated with all trials with condition 1, and then all trials with conditions 2.
I don't know how to ask R to put them in the correct order (i.e. trial 1 for 4 times in condition 1, then trial 1 for 4 times in condition 2,trial 2 for 4 times in condition 1, then trial 2 for 4 times in condition 2, and so on). If anyone has suggestions, Thank you.

ira ira
Answer

For the original question:

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

For the question from the comments:

Solution1:

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")

Solution2:

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