Modify a vector by rep()

Hello!

# I have got this vector: 
a <- c("1",  "2",  "3",  "4",  "5",  "6",  "7")
#[1] "1"  "2"  "3"  "4"  "5"  "6"  "7"

# and I would like to have this vector:
# [1]  1_A1  1_A2  1_A7  2_A1  2_A2  2_A7  3_A1  3_A2  3_A7  4_A1  4_A2  4_A7   5_A1  5_A2  5_A7  6_A1  6_A2  6_A7  7_A1  7_A2  7_A7


# My solution started with:
r1  <-  rep(a, each=3)
# [1]  "1"  "1"  "1"  "2"  "2"  "2"  "3"  "3"  "3"  "4"  "4"  "4"  "5"  "5"  "5"  "6"  "6"  "6"  "7"  "7"  "7"

# Then I created this vector:
b <- c("_A1","_A2","_A7")
# [1]  "_A1"  "_A2"  "_A7"

# And then I replicated the previous vector 7 times
r2 <- rep(b,times=7)  
# [1] "_A1"  "_A2"  "_A7" "_A1" "_A2" "_A7" "_A1" "_A2" "_A7" "_A1" "_A2" "_A7" "_A1" "_A2" "_A7" "_A1" "_A2" "_A7" "_A1" "_A2" "_A7"

Now I would like to combine vector r1 and vector r2 to achieve my desired vector. Any help?

Or is my solution quite cumbersome and there is a better solution? Maybe with a for-loop?

Thank you!

I don't know if it is that much quicker or easier, but you could use expand_grid(), then unite().

library(tidyverse)

a <- c("1",  "2",  "3",  "4",  "5",  "6",  "7")
b <- c("_A1","_A2","_A7")

expand_grid(a, b) %>% 
  unite("c", a:b, sep = "") %>% 
    pull()

[1] "1_A1" "1_A2" "1_A7" "2_A1" "2_A2" "2_A7" "3_A1" "3_A2" "3_A7" "4_A1" "4_A2" "4_A7" "5_A1" "5_A2" "5_A7" "6_A1" "6_A2" "6_A7" "7_A1" "7_A2" "7_A7"
2 Likes

Yes, thank you! Nice code!

I don't really understand the purpose of "c" in your code. It seems I can write anything instead of "c"...

But it works perfectly for my data.

1 Like

Yeah, you can write anything instead of "c". See comments below:

expand_grid(a, b) %>%  # creates a grid with all possibilities of a and b 
  unite("c", a:b, sep = "") %>%  # creates a new column 'c' from a and b, with no separator, removing the original cols.
    pull() # pulls all of it in to a vector.
1 Like

Here's an answer using just paste and rep:

# method 1
X <- paste0(
  rep(x = 1:7, each = 3),
  "_A",
  rep(x = c(1, 2, 7), times = 7)
)
X
#>  [1] "1_A1" "1_A2" "1_A7" "2_A1" "2_A2" "2_A7" "3_A1" "3_A2" "3_A7" "4_A1"
#> [11] "4_A2" "4_A7" "5_A1" "5_A2" "5_A7" "6_A1" "6_A2" "6_A7" "7_A1" "7_A2"
#> [21] "7_A7"

# method 2
a <- rep(x = as.character(x = 1:7), each = 3)
b <- c("_A1", "_A2", "_A7")
Y <- paste0(a, b)
Y
#>  [1] "1_A1" "1_A2" "1_A7" "2_A1" "2_A2" "2_A7" "3_A1" "3_A2" "3_A7" "4_A1"
#> [11] "4_A2" "4_A7" "5_A1" "5_A2" "5_A7" "6_A1" "6_A2" "6_A7" "7_A1" "7_A2"
#> [21] "7_A7"

# check
all.equal(target = X, current = Y)
#> [1] TRUE
1 Like

Also a nice solution. paste() was the function I didn't think of.

Thank you Yarnabrina and Williaml; now I've learned something.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.