Search code examples
rshinysplittextinputstrsplit

How can I define if statements depending on the type of the separation using strsplit in R?


I am trying to create a Shiny app using textInput. The idea is that the user could be able to enter a list of words in order to use it.

I have found this post which allows me to split the words into a vector. However, it depends how the user decides to enter the words in the app. I was wondering if it is possible to create if statements with the type of separation. For example, if the user writes something like this:

  1. word1,word2,word2 or
  2. word1 word2 word3 or
  3. word1, word2, word3 or another combinations.

The thing is that I need a final vector in order to use it later.

Examples of the type of separations that I want:

#1
unlist(strsplit("a, b, c", ", "))
[1] "a" "b" "c"

#2
unlist(strsplit("a,b,c", ","))
[1] "a" "b" "c"


#3
unlist(strsplit("a b c", " "))
[1] "a" "b" "c"

Is there a way to look at the type of separation? Like...

if sep="," or sep=", " or sep=" " { do something}

On the other hand, I would like to know if there is a possibility to have if statements if the user decides to put everything is lower case or upper case, in order to change all the words in only one type.

Does anyone can help me?

Thanks in advance

Regards


Solution

  • You can pass multiple separator to strsplit using |.

    #split on comma followed by zero or more whitespace OR one or more whitespace
    split_list <- function(x) unlist(strsplit(x, ',\\s*|\\s+'))
    
    split_list("a, b, c")
    #[1] "a" "b" "c"
    
    split_list("a,b,c")
    #[1] "a" "b" "c"
    
    split_list("a b c")
    #[1] "a" "b" "c"
    

    Use toupper/tolower to make all the words in upper or lower case respectively.