'Split character string forward slash and in brackets

I would split a character string which consist of data look like this: 105/44(64) I would split this in 3 columns:

  • "105" called "systole"
  • "44" called "diastole"
  • "64" called "map"

How can I do that? I have not enough capacity to extract this out the other questions about split strings... I think I have to do it with stringr from tidyverse?



Solution 1:[1]

Using strsplit on non-digits \\D. No packages needed.

strsplit(x, '\\D', perl=TRUE) |>
  do.call(what=rbind.data.frame) |>
  setNames(c('systole', 'diastole', 'map'))
#   systole diastole map
# 1     105       44  64
# 2     106       43  61

W/o pipes:

setNames(do.call(rbind.data.frame, strsplit(x, '\\D', perl=TRUE)), 
         c('systole', 'diastole', 'map'))
#   systole diastole map
# 1     105       44  64
# 2     106       43  61

Data:

x <- c('105/44(64)', '106/43(61)')

Solution 2:[2]

In base R, we can make use of read.csv/read.table after creating a common delimiter

read.csv(text = trimws(gsub("[[:punct:]]", ",", str1), whitespace= ","), 
   header = FALSE, col.names = c("systole", "diastole", "map"))

-output

   systole diastole map
1     105       44  64
2     106       43  61

data

str1 <- c('105/44(64)', '106/43(61)')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jay.sf
Solution 2 akrun