Reputation: 332
I hope I am using the correct terminology here.
I have two vectors,
i_25_points <- 130:134
j_25_points <- 65:69
I want to combine them into pairs, like a matrix almost but then collapse them down into a string like below
130;65|130;66|130;67....134;65|134;66|134;67|134;68|134;69
How can I combine the? My original thought is to create the pairs by nested for loops and appending them together.
But there must be a more slick way to do so.
Upvotes: 0
Views: 706
Reputation: 76
An option with expand.grid and paste
i_25_points <- 130:134
j_25_points <- 65:69
x <- expand.grid(j_25_points ,j_25_points )
paste(x[,1], x[,2], sep = ";", collapse = "|")
Upvotes: 1
Reputation: 887971
An option with rep
and paste
paste(rep(i_25_points, each = length(j_25_points)),
rep(j_25_points, length(i_25_points)), sep=";", collapse="|")
#[1] "130;65|130;66|130;67|130;68|130;69|131;65|131;66|131;67|131;68|131;69|132;65|132;66|132;67|132;68|132;69|133;65|133;66|133;67|133;68|133;69|134;65|134;66|134;67|134;68|134;69"
Or using tidyverse
library(tidyverse)
crossing(i_25_points, j_25_points) %>%
unite(newCol, i_25_points, j_25_points, sep=":") %>%
summarise(newCol = str_c(newCol, collapse="|")) %>%
pull(newCol)
i_25_points <- c(130, 131, 132, 133, 134)
j_25_points <- 65:69
Upvotes: 0
Reputation: 51612
You can use outer
to create all the possible pairs, and simply paste
, i.e.
paste(outer(x, y, paste, sep = ';'), collapse = '|')
Upvotes: 4