Using string characters to create line breaks (push to new rows)

Hi,

I have a long line of results taken from an Excel file that I want to organize in R. Here is the sample:

df <- c("1.24 [.71, 1.98], 0.86[0.45, 1.29] , 0.97[0.68, 1.17]")

And my goal is to convert to the following form:

1.24 [.71, 1.98]
0.86 [0.45, 1.29]
0.97 [0.68, 1.17]

Please let me know.

Happy new year!

Happy New Year! Here is one way to create new rows.

library(tidyverse)

df <- data.frame(col = c("1.24 [.71, 1.98], 0.86[0.45, 1.29], 0.97[0.68, 1.17]"))

df
#>                                                    col
#> 1 1.24 [.71, 1.98], 0.86[0.45, 1.29], 0.97[0.68, 1.17]

df %>%
  mutate(col = str_replace_all(col, '], ', ']|')) %>%
  separate_rows(col, sep = '\\|')
#> # A tibble: 3 × 1
#>   col             
#>   <chr>           
#> 1 1.24 [.71, 1.98]
#> 2 0.86[0.45, 1.29]
#> 3 0.97[0.68, 1.17]

Created on 2023-01-01 with reprex v2.0.2.9000

2 Likes

Thanks so much Scotty!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.