How do you move every other line to the line before it in R?

Viewed 25

I have read in a list of lines int R and need to take the line with the name on it and append it to the line below it so it reads as one row.

The current output is:

[1] "Joe Exotic"                  "Tiger King, Lead"            "Carole Baskin"              
[4] "Husband Killer, Tiger Queen" "Doc Antle"                   "Tiger Person, Swinger" 

And I would like it to look like:

[1] "Joe Exotic, Tiger King, Lead"               "Carole Baskin, Husband Killer, Tiger Queen"
[3] "Doc Antle, Tiger Person, Swinger"  

Solutions in the tidyverse would be ideal. Thank you.

2 Answers

Put the vector into a matrix with 2 rows and apply the function toString() to each column.

apply(matrix(x, 2), 2, toString)

# [1] "Joe Exotic, Tiger King, Lead"              
# [2] "Carole Baskin, Husband Killer, Tiger Queen"
# [3] "Doc Antle, Tiger Person, Swinger" 

Data

x <- c("Joe Exotic", "Tiger King, Lead", "Carole Baskin", "Husband Killer, Tiger Queen", "Doc Antle", "Tiger Person, Swinger")

We can split the data into a list by creating a grouping index with gl and then paste

unname(sapply(split(x, as.integer(gl(length(x), 2, length(x)))), toString))

data

x <- c("Joe Exotic", "Tiger King, Lead", "Carole Baskin", 
      "Husband Killer, Tiger Queen", "Doc Antle", "Tiger Person, Swinger")
Related