1

I need to create a Vector combining the numbers c(1:10) and the Terms c("-KM","-COX"), so that it would turn out like this:

c("1-KM", "1-COX", "2-KM", "2-COX", "3-KM", "3-COX", ...) 

I have tried using expand.grid to do that, however it returns a data frame, and I would need it to return a vector. Any help in how I could do that?

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360

2 Answers2

1

Try this version:

apply(expand.grid(v1, v2), 1, function(x) trimws(paste0(x[1], x[2])))

 [1] "1-KM"   "2-KM"   "3-KM"   "4-KM"   "5-KM"   "6-KM"   "7-KM"   "8-KM"  
 [9] "9-KM"   "10-KM"  "1-COX"  "2-COX"  "3-COX"  "4-COX"  "5-COX"  "6-COX" 
[17] "7-COX"  "8-COX"  "9-COX"  "10-COX"

Data:

v1 <- c(1:10)
v2 <- c("-KM", "-COX")
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

After expand.grid you can use paste to get a vector from the returned data.frame.

do.call(paste0, expand.grid(1:10, c("-KM","-COX")))
# [1] "1-KM"   "2-KM"   "3-KM"   "4-KM"   "5-KM"   "6-KM"   "7-KM"   "8-KM"  
# [9] "9-KM"   "10-KM"  "1-COX"  "2-COX"  "3-COX"  "4-COX"  "5-COX"  "6-COX" 
#[17] "7-COX"  "8-COX"  "9-COX"  "10-COX"
GKi
  • 37,245
  • 2
  • 26
  • 48