1
votes

I would like to avoid using for loop in following example. Goal is to repeat string vector multiple times with different second part which changes each repetition. Is that possible?

str2D = mtcars 
Vector = c(10,20)

Dimen = dim( str2D )
nn = c()
  for ( i in Dimen[2]*(1:length(Vector)) ){
    nn[ (i+1-Dimen[2]): i ] = rep(paste("|d",Vector[i/Dimen[2]],sep=""), Dimen[2] )
  }

Name = paste( rep(names(str2D) , length(Vector) ),nn,sep="")

Correct result for "Name" vector is following: "mpg|d10" "cyl|d10" "disp|d10" "hp|d10" "drat|d10" "wt|d10" "qsec|d10" "vs|d10" "am|d10" "gear|d10" "carb|d10" "mpg|d20" "cyl|d20" "disp|d20" "hp|d20" "drat|d20" "wt|d20" "qsec|d20" "vs|d20" "am|d20" "gear|d20" "carb|d20"

Thank you

1

1 Answers

1
votes

I don't quite understand the end goal here but at least this achieves your desired output without a loop:

Name <- paste0(paste(names(mtcars)), "|d", rep(1:2, each = length(names(mtcars))), "0")

> Name
 [1] "mpg|d10"  "cyl|d10"  "disp|d10" "hp|d10"   "drat|d10" "wt|d10"   "qsec|d10"
 [8] "vs|d10"   "am|d10"   "gear|d10" "carb|d10" "mpg|d20"  "cyl|d20"  "disp|d20"
[15] "hp|d20"   "drat|d20" "wt|d20"   "qsec|d20" "vs|d20"   "am|d20"   "gear|d20"
[22] "carb|d20"