How to repeat a sequence in R but adjust values in the vector when repeated?

Viewed 53

Here is an example:

This line of code repeats each subject specified twice:

subject <- rep(c("maths", "english", "science"), each = 2)

So output in the console for "subject" is:

# [1] "maths"   "maths"   "english" "english" "science" "science"

How can I adjust my code to make a minor change to the vector which is repeated? I would like the variable "subject" to produce the following when run:

"maths.A" "maths.B" "english.A" "english.B" "science.A" "science.B"

This would be very useful when generating a lot of data. Entering the names manually would be very inefficient.

I'm not sure if there is a way to do this, but any ideas are welcome :)

5 Answers

You can do

paste(rep(c("maths", "english", "science"), each = 2), c("A", "B"), sep = ".")
#> [1] "maths.A"   "maths.B"   "english.A" "english.B" "science.A" "science.B"

Here is another base R option

x <- c("maths", "english", "science")
y <- c("A","B")
do.call(paste,c(rev(expand.grid(y,x)),sep = "."))

which gives

> do.call(paste,c(rev(expand.grid(y,x)),sep = "."))
[1] "maths.A"   "maths.B"   "english.A" "english.B" "science.A" "science.B"

We can also use outer

c(outer(x, y, FUN = paste, sep="."))

data

x <- c("maths", "english", "science")
y <- c("A","B")

Perhaps try

with(expand.grid(c("A", "B"), c("maths", "english", "science")), paste0(Var2, ".", Var1))

Output

[1] "maths.A"   "maths.B"   "english.A" "english.B" "science.A" "science.B"

you could also use sapply or even outer:

c(sapply(c("maths", "english", "science"), paste, c("A","B"),sep="."))
[1] "maths.A"   "maths.B"   "english.A" "english.B" "science.A" "science.B"
Related