0

If I have the numbers character vector below, how can I (presumably using a for loop?) paste the strings into a series of sentences, where the number of strings used depends on the iteration of the loop? Ultimately, the output I want should be such that the first sentence is something like 'one', the second is 'one and two', the third 'one and two and three', etc. The specifics don't really matter, I'm just after the general technique I could use to achieve something like this within R.

numbers <- c("one", "two", "three", "four")

Example desired output:

> sentences[1]
"one"
> sentences[2]
"one and two"
> sentences[3]
"one and two and three"
> sentences[4]
"one and two and three and four"

I've thought about this for a while, but I haven't yet come up with a way to achieve this. I assume a solution would make use of some sort of for loop and probably the paste() function, but I wouldn't mind at all if there was a solution which didn't include these.

1
  • 5
    A one-liner solution would be sapply(seq(length(numbers)), function(x) paste(numbers[seq(x)], collapse = ' and ')) Commented Jun 11, 2019 at 12:16

1 Answer 1

1

You could use Reduce

numbers <- c("one", "two", "three", "four")
Reduce(function(x,y) paste(x,y, sep=" and "), numbers, accumulate=TRUE)
#[1] "one"                            "one and two"                   
#[3] "one and two and three"          "one and two and three and four"

or if you don't need the and between simply

Reduce(paste, numbers, accumulate = T)
#[1] "one"                "one two"            "one two three"     
#[4] "one two three four"
Sign up to request clarification or add additional context in comments.

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.