Home > Blockchain >  Use all elements as an argument in while function
Use all elements as an argument in while function

Time:01-06

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:

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"

CodePudding user response:

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"
  •  Tags:  
  • Related