Replace string gsub in R

Viewed 91

how do i parse this string in R so that it will look like the following? I'm trying to do this through regular expression through gsub(), but not getting any luck

Input:

"dag{D<-{G}; A<-{D}; A<-{G}; A<-{Q}}"

Output:

"D<-G;A<-D;A<-G;A<-Q"

I've tried:

gsub("dag{(.*)}","","dag{D<-{G}; A<-{D}; A<-{G}; A<-{Q}}")

5 Answers

Is this good for you ?

gsub(pattern = "dag|\\{|\\}|[[:space:]]", replacement = "", x = "dag{D<-{G}; A<-{D}; A<-{G}; A<-{Q}}")

With stringr you could try:

str <- "dag{D<-{G}; A<-{D}; A<-{G}; A<-{Q}}"


library(stringr)

str_remove_all(str, "(dag)|[ {}]")
#> [1] "D<-G;A<-D;A<-G;A<-Q"

Created on 2021-08-31 by the reprex package (v2.0.0)

As this is a dag format, we could use dedicated packages to import:

library(ggdag)
library(dagitty)

# read dag format
dag <- dag("dag{D<-{G}; A<-{D}; A<-{G}; A<-{Q}}") 

dag
# dag {
# A
# D
# G
# Q
# dag
# D -> A
# G -> A
# G -> D
# Q -> A
# }

# plot
ggdag(dag) + theme_dag()

enter image description here

We can try

> gsub("[(dag){} ]", "", "dag{D<-{G}; A<-{D}; A<-{G}; A<-{Q}}")
[1] "D<-G;A<-D;A<-G;A<-Q"

If you want to create a DAG, you can try the following code using igraph package

g <- graph_from_data_frame(
  matrix(
    unlist(
      regmatches(x, gregexpr("\\w+", x))
    )[-1],
    ncol = 2, byrow = TRUE
  )[, 2:1]
)

such that

> g
IGRAPH 9786b7a DN-- 4 4 --
+ attr: name (v/c)
+ edges from 9786b7a (vertex names):
[1] G->D D->A G->A Q->A

enter image description here

Here is a regex find all approach which matches all the edge relationships:

input <- "dag{D<-{G}; A<-{D}; A<-{G}; A<-{Q}}"
output <- regmatches(input, gregexpr("[A-Z]+<-\\{[A-Z]+\\}", input))[[1]]
output <- paste(gsub("[{}]", "", output), collapse=";")
output

[1] "D<-G;A<-D;A<-G;A<-Q"

This answer is fairly robust as it does not assume anything about the text surrounding the closure of graph edges. Rather, it just matches the edges and then strips off the curly braces.

Related