-1

This is my first time posting; please let me know if I'm doing any beginner mistakes. In my specific case I have a vector of strings, and I want to collapse some adjacent rows. I have one vector indicating the starting position and one indicating the last element. How can I do this?

Here is some sample code and my approach that does not work:

text <- c("cat", "dog", "house", "mouse", "street")
x <- c(1,3)
y <- c(2,5)
result <- as.data.frame(paste(text[x:y],sep = " ",collapse = ""))

In case it's not clear, the result I want is a data frame consisting of two strings: "cat dog" and "house mouse street".

coip
  • 1,312
  • 16
  • 30
Jo el
  • 11
  • 1
  • Hi Jo el. Welcome to StackOverflow! Please read the info about [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and how to give a [minimale reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610).That way you can help others to help you! By reading the links above you will see that it would be better if you also showed what you want to see. That way we would know if you wanted the strings to be in columns or rows of the resulting data.frame. – dario Feb 19 '20 at 15:39
  • Hi dario. Sorry that I was not clear enough, I though my last sentence would clarify how I want the result to look like. – Jo el Feb 19 '20 at 16:01

4 Answers4

2

Not sure this is the best option, but it does the job,

sapply(mapply(seq, x, y), function(i)paste(text[i], collapse = ' '))
#[1] "cat dog"            "house mouse street"
Sotos
  • 51,121
  • 6
  • 32
  • 66
2

Either use base R with

mapply(function(.x,.y) paste(text[.x:.y],collapse = " "), x, y)

or use the purrr package as

map2_chr(x,y, ~ paste(text[.x:.y],collapse = " "))

Both yield

# [1] "cat dog"            "house mouse street"

The output as a data frame depends on the structure you want: rows or columns

DeltaKappa
  • 171
  • 7
1

I think you want

result <- data.frame(combined = c(paste(text[x[1]:y[1]], collapse = " "), 
                                  paste(text[x[2]:y[2]], collapse = " ")))

Which gives you

result
#>             combined
#> 1            cat dog
#> 2 house mouse street
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
0

Another base R solution, using parse + eval

result <- data.frame(new = sapply(paste0(x,":",y),function(v) paste0(text[eval(parse(text = v))],collapse = " ")),
                     row.names = NULL)

such that

> result
                 new
1            cat dog
2 house mouse street
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81