4

I would like to divide rows in R in certain columns.. in my example, I would like to make a new row every time there is a \n.

Any ideas? Preferably, I would like to do that using tidyverse.

Reprex:

library(dplyr)

tibble(
  x = c("Row 1", "Row 2\nRow 3", "Row 4"),
  y = c("Value 1", "Value 2\nValue 3", "Value 4")
)
#> # A tibble: 3 x 2
#>   x              y                 
#>   <chr>          <chr>             
#> 1 Row 1          Value 1           
#> 2 "Row 2\nRow 3" "Value 2\nValue 3"
#> 3 Row 4          Value 4

Created on 2019-12-01 by the reprex package (v0.3.0)

Desired output:

#> # A tibble: 4 x 2
#>   x     y
#>   <chr> <chr>                                          
#> 1 Row 1 Value 1                                        
#> 2 Row 2 Value 2                                        
#> 3 Row 3 Value 3                                        
#> 4 Row 4 Value 4
FMM
  • 1,857
  • 1
  • 15
  • 38
  • Does this answer your question? [Split comma-separated strings in a column into separate rows](https://stackoverflow.com/questions/13773770/split-comma-separated-strings-in-a-column-into-separate-rows) – Cole Dec 01 '19 at 16:13
  • Well made question that seems to be a duplicate. https://stackoverflow.com/questions/15347282/split-delimited-strings-in-a-column-and-insert-as-new-rows – Cole Dec 01 '19 at 16:14

1 Answers1

4

One option is separate_rows with sep = "\n"

library(dplyr)
library(tidyr)
df1 %>%
   separate_rows(x, y, sep = "\n")
# A tibble: 4 x 2
#  x     y      
#  <chr> <chr>  
#1 Row 1 Value 1
#2 Row 2 Value 2
#3 Row 3 Value 3
#4 Row 4 Value 4

data

df1 <- tibble(
  x = c("Row 1", "Row 2\nRow 3", "Row 4"),
  y = c("Value 1", "Value 2\nValue 3", "Value 4")
)
akrun
  • 874,273
  • 37
  • 540
  • 662