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)
Sara n
  • 21
  • 2
  • Does this answer your question? [Paste multiple columns together](https://stackoverflow.com/questions/14568662/paste-multiple-columns-together) – shadowtalker Nov 27 '22 at 04: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))`. – dcarlson Nov 27 '22 at 05:19

2 Answers2

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.

shadowtalker
  • 12,529
  • 3
  • 53
  • 96
  • 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 – Sara n Nov 27 '22 at 05:41
  • @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. – shadowtalker Nov 27 '22 at 06:28
  • 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)` – Isaiah Nov 27 '22 at 07:24
2

I think you need rep with each:

df <- data.frame(my_col = rep(rep(c("hello", "hi"), each=130),2))
TarJae
  • 72,363
  • 6
  • 19
  • 66