Home > Back-end >  Split a string and append it to a vector
Split a string and append it to a vector

Time:01-21

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!

CodePudding user response:

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)

CodePudding user response:

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')

CodePudding user response:

An alternative is stringr::str_split

str_split(c('F2', 'A1/B1', 'X3.2', 'M3fn', 'E2/Q2'), pattern = "/") %>% 
  unlist()
[1] "F2"   "A1"   "B1"   "X3.2" "M3fn" "E2"   "Q2"  
  •  Tags:  
  • Related