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 
2

1 Answer 1

3

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") ) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.