在 while 函数中使用所有元素作为参数
Use all elements as an argument in while function
我有以下功能:
function1 <- function(x){
while(grepl("^|", x, fixed = TRUE)){
x <- gsub("\^\|", "\|", x)
}
return(x)
}
应该可以兑换^|用|,同时还有一个^|。
当我执行以下操作时:
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
它并没有减少所有的^|在第二个元素中,因为第一个元素没有 ^|因此 while 函数停止。
如何遍历所有元素的函数?结果应该是:
[1] "hallo|hallo" "hallo|hallo"
你可以使用 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"
我有以下功能:
function1 <- function(x){
while(grepl("^|", x, fixed = TRUE)){
x <- gsub("\^\|", "\|", x)
}
return(x)
}
应该可以兑换^|用|,同时还有一个^|。
当我执行以下操作时:
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
它并没有减少所有的^|在第二个元素中,因为第一个元素没有 ^|因此 while 函数停止。
如何遍历所有元素的函数?结果应该是:
[1] "hallo|hallo" "hallo|hallo"
你可以使用 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"