R 对自定义函数进行矢量化

R 对自定义函数进行矢量化,r,function,vectorization,R,Function,Vectorization,我编写此函数是为了返回某个字符之前的字符串,如下所示: strBefore <- function(find, x, last = FALSE, occurence) { # Checking. if (class(x)[1] != "character") { stop("The strBefore function only supports objects of character class.") } # Getting the place of the find,

我编写此函数是为了返回某个字符之前的字符串,如下所示:

strBefore <- function(find, x, last = FALSE, occurence) {

  # Checking.
  if (class(x)[1] != "character") { stop("The strBefore function only supports objects of character class.") }

  # Getting the place of the find, and handling both caes of last.
  fullPlace <- gregexpr(find, x)[[1]] # Gets the location of the occurences of find in x.

  # Handling the case where last is TRUE.
  if (last == TRUE) { place <- max(fullPlace) # Grabbing the latest character index if last is TRUE.
  } else { place <- min(fullPlace) } # Otherwise, getting the first space.

  # Handles the occurrenceargument if given.
  if (!missing(occurrence)) { place <- fullPlace[occurrence] }

  # Subsetting the string.
  xlen <- nchar(x) # Getting the total number of characters in the string.
  x <- substr(x, 1, place - 1) # Minus 1 because we don't want to include the first hit for find.
  return(x)

}
但是,如果我在字符向量上使用它,它会在向量中与第一项相同的位置剪切每个项:

> test <- c("Hello World", "Hi There", "Why Hello")
> test2 <- strBefore(" ", test)
> test2
[1] "Hello" "Hi Th" "Why H"

这在某种程度上解决了我的问题……但有没有一种方法可以更干净地执行此操作,而不必使用
apply
函数我不是在寻找一个解决方案来解决strb之前所做的事情,而是一个如何对自定义函数进行矢量化的解决方案。谢谢您的时间。

您可以像这样对函数进行向量化
向量化(strBefore,“x”)(“”,test)
。使用不符合您要求的示例输入遍历您的函数,并找出它在何处中断。
您可能希望查看
regmatches()
,它与正则表达式一起,可以提供您想要的,而不必编写那么多自定义函数。
Vectorize(strBefore,“x”)
返回一个函数,该函数将参数
x
矢量化。所以你可以在以前做类似的事情
> test <- c("Hello World", "Hi There", "Why Hello")
> test2 <- strBefore(" ", test)
> test2
[1] "Hello" "Hi Th" "Why H"
> test <- c("Hello World", "Hi There", "Why Hello")
> test2 <- sapply(test, function(x) strBefore(" ", x))
> test2
Hello World    Hi There   Why Hello 
    "Hello"        "Hi"       "Why"