1

I have a vector Names<-c("A", "B", "C")

And I would ultimately like something like this
c("A_Mean", "A_Median", "A_InGroupVar", "B_Mean", "B_Median", "B_InGroupVar", "C_Mean", "C_Median", "C_InGroupVar")

I have tried the paste function c(paste(Names, "_Mean"), paste(Names, "_Median"), paste(Names, "_InGroupvar"))

But I need the vector to be ordered by Name. I know I could easily do this in a loop but I am looking for a more elegant solution.

2 Answers 2

4

Here is a raw approach:

Names <- rep(c("A", "B", "C"), each=3)
Stats <- rep(c("Mean", "Median", "InGroupVar"), 3)
paste(Names, Stats, sep="_")
[1] "A_Mean"       "A_Median"     "A_InGroupVar" "B_Mean"       "B_Median"    
[6] "B_InGroupVar" "C_Mean"       "C_Median"     "C_InGroupVar"
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you that's exactly what I was after! Seems so obvious now
You can also do this without having to call rep a second time. paste0(Names, "_", c("Mean", "Median", "InGroupVar"))
Sure, but I deliberately chose to show the different ways to use rep. But thank you for your contribution.
3

I like sprintf better for this particular problem:

Names <- c("A", "B", "C")

sprintf("%s_%s", 
        rep(Names, each = 3), 
        c("Mean", "Median", "InGroupVar"))
# [1] "A_Mean"       "A_Median"     "A_InGroupVar" "B_Mean"      
# [5] "B_Median"     "B_InGroupVar" "C_Mean"       "C_Median"    
# [9] "C_InGroupVar"

Alternatively, this also works, but gives you the results in a different order:

do.call(paste, 
        c(expand.grid(
          Names, c("Mean", "Median", "InGroupVar")), 
          sep = "_"))   
# [1] "A_Mean"       "B_Mean"       "C_Mean"       "A_Median"    
# [5] "B_Median"     "C_Median"     "A_InGroupVar" "B_InGroupVar"
# [9] "C_InGroupVar"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.