1

I need following: repeat two values, each 3 times: I can do it with

rplcts = rep(c("Trt","Ctl"), each=3) 

but I also want to add to each string in one group following values: 1,2,3 so, at the end I need this:

"Ctl1" "Ctl2" "Ctl3" "Trt1" "Trt2" "Trt3" 

Is there a smart way to do it in r?

2
  • 1
    paste0(rep(c("Trt","Ctl"), each=3), c(1, 2, 3))? Commented Nov 25, 2015 at 14:01
  • 1
    paste0(rplcts, 1:3) Commented Nov 25, 2015 at 14:02

2 Answers 2

1

You essentially only need to paste two vectors.

paste0(rep(c("Trt", "Ctl"), each = 3), rep(1:3, 2)) 

A more general solution could be

mySeq <- function(groups, each){ paste0(rep(groups, each=each), 1:each) # Element recycling will match the length } mySeq(c("Trt", "Ctl"), 3) 
Sign up to request clarification or add additional context in comments.

3 Comments

Due to element-recycling, you could omit the second call to rep.
I often avoid taking advantage of recycling because I'm terrified of what happens when the one vector's length isn't a multiple of the other's length. But in the controlled state of that function, I think it works nicely. Good catch.
I agree with you (better safe than sorry), but in this very controlled case it's acceptable.
0

Here is is with handy magrittr syntax:

library(magrittr) c("Trt", "Ctl") %>% rep(each = 3) %>% paste0(c(1, 2, 3)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.