1

I have a character vector where the string elements either have or don't have a slash(/).

sem_tags <- ('F2', 'A1/B1', 'X3.2', 'M3fn', 'E2/Q2')

I want those tags that have the slash to be stored as two separate tags so that in the end I get

new_sem_tags <- ('F2', 'A1', 'B1', 'X3.2', 'M3fn', 'E2', 'Q2')

Here is what I tried so far.

new_sem_tags <- c()
for (i in 1:length(sem_tags)){
  if (grepl("/", i)){
    append(new_sem_tags, str_split(i, '/'))
  } else {
    appendnew_sem_tags, i)
  }
  i = i+1
}

Unfortunately, this doesn't work. When I try every function separately, e.g., splitting and appending they seem to do the job. However, what I noticed is that appending returns the output but doesn't 'store' the output. Could that be the problem? If yes, how can I overcome it?

Thanks in advance!

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
armgar
  • 11
  • 4
  • 1
    In R, things are almost never stored/modified unless you assign the result with `<-` or `=`. If you start with `x <- 5`, `x+1` will print 6 but not change `x`--if you want to change `x` you need `x <- x + 1`. Similarly `append(x, 10)` will print `5 10`, but if you want to modify `x` you need `x <- append(x, 10)`. In your case, you could use `new_sem_tags <- append(new_sum_tags, ...)` (though lovalery's solution is cleaner). – Gregor Thomas Jan 20 '22 at 14:56
  • @GregorThomas thank you for the comment! I tried it as well but it gave me a weird result. I got an integer vector `(1, 2, 3, 4, 5 ... )` which reached to the length of the `sem_tags` vector. – armgar Jan 21 '22 at 13:55

2 Answers2

5

Using base R, you can do:

Reprex

sem_tags <- c('F2', 'A1/B1', 'X3.2', 'M3fn', 'E2/Q2')

unlist(strsplit(sem_tags, "/"))
#> [1] "F2"   "A1"   "B1"   "X3.2" "M3fn" "E2"   "Q2"

Created on 2022-01-20 by the reprex package (v2.0.1)

lovalery
  • 4,524
  • 3
  • 14
  • 28
2

We can scan it in:

scan(text = sem_tags, what = "", sep = "/", quiet = TRUE)
## [1] "F2"   "A1"   "B1"   "X3.2" "M3fn" "E2"   "Q2"  

Note

The question has a syntax error in the definition of the input so we used this.

sem_tags <- c('F2', 'A1/B1', 'X3.2', 'M3fn', 'E2/Q2')
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341