3

I have a string "c(\"AV\", \"IM\")", which I'm trying to transform into the string "AV IM".

My issue is that I can't unlist() or flatten() this, as it's a character, and neither paste() nor stringr::str_c() work, since it's technically still 1 character value.

Any ideas how I can do this?

Tidyverse solutions preferred, if possible.

EDIT: I know this can be solved via regex, but I feel like this is more a "fundamental" problem to be solved string-level than it is a regex problem, if that makes any sense.

Evan O.
  • 1,553
  • 2
  • 11
  • 20
  • iI you're the one responsible for getting your data in this shape (maybe using `as.character(substitute(...))` ?) you'd be better off solving this upstream. – moodymudskipper Jul 08 '18 at 14:37
  • i'm with you there. Definitely want to fix this early. The problem is I'm not really sure how. I think it's a string-level issue (not character-level, where regex makes sense). – Evan O. Jul 09 '18 at 00:52
  • what is the instruction that outputs this string ? – moodymudskipper Jul 09 '18 at 07:25

4 Answers4

4

Not sure how you got here, but this as presented would be an eval/parse situation. However, as noted in many other answers on this site, there's almost always a better way of preparing your data so you end up in a more R-friendly form. See, for starters, What specifically are the dangers of eval(parse(...))?.

> a <- "c(\"AV\", \"IM\")"
> (b <- eval(parse(text=a)))
[1] "AV" "IM"
> paste(b, collapse=" ")
[1] "AV IM"
Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142
1

You can also consider to use regular expression to replace all symbols and the beginning c.

s <- "c(\"AV\", \"IM\")"

s_vec <- strsplit(s, split = ",")[[1]]

gsub("[[:punct:]]|^c", "", s_vec)
# [1] "AV"  " IM"
www
  • 38,575
  • 12
  • 48
  • 84
1

Well it is not quite easy how you got here. You can use eval-parse, though it is not vectorized. And also it is slow. Thus you need a regular expression:

 a <- "c(\"AV\", \"IM\")"
 stringr::str_extract_all(a,"\\w+(?!\\()")
[[1]]
[1] "AV" "IM"
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

Other answers output a vector. My understanding is you want a space-delimited list of your strings.

library(dplyr)

a <- "c(\"AV\", \"IM\")"

a %>%
  gsub("c(", "", ., fixed=TRUE) %>% 
  gsub("\"", "", ., fixed=TRUE) %>% 
  gsub(",",  "", ., fixed=TRUE) %>% 
  gsub(")",  "", ., fixed=TRUE)

Output

"AV IM"

EDIT Or simply (from @www's answer):

a %>%
  gsub("[[:punct:]]|^c",  "", .)
Jack Brookes
  • 3,720
  • 2
  • 11
  • 22