1

I have a list, that is a string. In this string, the characters are separated by either a ";" or ",". So I have to use a "strsplit". With this, in this example, I end up with 3 list, where 2 of those lists have 3 elements and the last only will have 2 elements in the list.

mylist = c("ac*, be, cd*; daa, efae*, fge*; gefa*, h")
Liste <- strsplit(strsplit(mylist , ";")[[1]], ",")

The reason for, using "strsplit" like this, is that when I have a ";" in my string and "," as a logical OR, then it acts like a logical AND, that means I have to use one element from each list, later in my code.

So the output of Liste will be

[[1]]
[1] "ac*"  " be" " cd*"

[[2]]
[1] " daa" " efae*" " fge*"

[[3]]
[1] " gefa*" " h"

What I am trying to avoid, is the use of the double for-loop, and maybe make the code faster, if it is possible.

so now I am using a nested for-loop, to look at each element in mylist.

for (c in 1:length(Liste)){
  for (d in 1:length(Liste[[c]])){
    # Extracting last character, matching if it is a wildcard
    # Liste[[c]][d] Prints all elements from the list
    # I need the double for-loop for this check
    if (stri_sub(Liste[[c]][d],-1,-1) == '*')
        DO SOMETHING
  }
}

What else can be done here?

2 Answers 2

3

You can try:

library(purrr)
walk(unlist(Liste),
     function(x) if (stri_sub(x,-1,-1) == '*')
                   DO SOMETHING
     )
Sign up to request clarification or add additional context in comments.

1 Comment

This is working, but I am ending using @Florian's code :)
2

It of course depends on what you want to do in those cases, but it seems stri_sub is vectorized, so you could make use of that. For example, to return all elements that match your condition, you could do

lapply(Liste, function(x) {x[stri_sub(x,-1,-1)=='*']})

which outputs

[[1]]
[1] "ac*"  " cd*"

[[2]]
[1] " efae*" " fge*" 

[[3]]
[1] " gefa*"

Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.