1

I was wondering if anyone could help me concencate two vectors of strings:

For example: hello and hi, that repeat 130 times in a dataframe.

When in the dataframe column I would like for the order to be hello, (130 times) followed by hi (also 130 times), then hello (130 more times), then hi (130 times) again. So they should appear 4 times total (2 times each in order)

This is what I tried so far but it does not seem to work

hello <- c(rep( "hello", 130))
hi<- c(rep( "hi", 130)) 
style <- c(hello, hi, hello, hi)
2
  • Does this answer your question? Paste multiple columns together Commented Nov 27, 2022 at 4:11
  • Here are a couple of options: style <- data.frame(greeting=paste(hello, hi, hello, hi)) or style <- data.frame(greeting=rep("hello hi hello high", 130)). Commented Nov 27, 2022 at 5:19

2 Answers 2

2

The general solution to string concatenation in R is the paste function. In this case, you just paste the same vectors multiple times:

hello <- rep("hello", 130)
hi <- rep("hi", 130)
result <- paste(hello, hi, hello, hi)
print(result)

There are other ways to handle this as well, e.g. using sprintf. I suggest consulting ?paste for details on usage.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so so much for your help! I will look up paste right away. However, I think I may have been confusing in my post because I wanted hello to appear 130 times, then hi, and then hello and so on. When I typed in what you just provided, I got hello followed by hi 130 times. Would you know how I would be able to get first hello 130 times and then hi 130 times? Again thank you for your help
@Saran use the c function to concatenate vectors. It's essential to give examples of desired inputs and outputs when asking questions, to prevent misunderstandings like this.
Welcome to SO Sara! :-) Shadowtalker's revised code is: hello <- rep("hello", 130) hi <- rep("hi", 130) result <- c(hello, hi, hello, hi) print(result)
2

I think you need rep with each:

df <- data.frame(my_col = rep(rep(c("hello", "hi"), each=130),2))

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.