Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use all elements as an argument in while function

I have the following function:

function1 <- function(x){
  while(grepl("^|", x, fixed = TRUE)){
    x <- gsub("\\^\\|", "\\|", x)
  }
  return(x)
}

It is supposed to exchange ^| with |, while there is still a ^|.

When i do the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

x <- c("hallo^|hallo", "hallo^^|hallo")
function1(x)
[1] "hallo|hallo"  "hallo^|hallo"
Warning messages:
1: In while (grepl("^|", x, fixed = TRUE)) { :
  the condition has length > 1 and only the first element will be used
2: In while (grepl("^|", x, fixed = TRUE)) { :
  the condition has length > 1 and only the first element will be used

it doesnt reduce all the ^| in the second element, because the first element is free of ^| and therefore the while function stops.

How can i iterate the function through all elements? The result should be:

[1] "hallo|hallo"  "hallo|hallo"

>Solution :

You could use any:

function1 <- function(x){
  while(any(grepl("^|", x, fixed = TRUE))) {
    x <- gsub("\\^\\|", "\\|", x)
  }
  return(x)
}
  
x <- c("hallo^|hallo", "hallo^^|hallo")

function1(x)
#> [1] "hallo|hallo" "hallo|hallo"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading