r函数不返回任何结果

时间:2017-04-12 09:12:07

标签: r function

我创建了以下功能。 R应该返回1但是我没有给出任何结果?

phrasedis <- function(string, phrase1, phrase2,n) { 
  char1 <- unlist(gregexpr(phrase1,string))
  char2 <- unlist(gregexpr(phrase2,string))

    for  ( i in 1: 2) {
      for (j in 1: 2) {
         pos1[i] <- sapply(strsplit(substr(text, 0,char1[i]-1),"\\s"),length)+1
         pos2[j] <- sapply(strsplit(substr(text, 0,char2[j]-1),"\\s"),length)+1
         dist <- pos2[i] - pos1[j]

         a <- ifelse(pos1[i]>0 & pos2[j]>0 & dist>0 & dist<=6,1,0)
         if (a==1) break
         return(a)
      }

    }
}

text <- "phone rang a b c d e f z y z phone rang but no answer"
b <- sapply(text, FUN=function(str) phrasedis(str,"phone rang" , "no answer",6))

如果电话铃声和无应答之间的距离小于6个字,它应该返回1,否则返回0。 非常感谢你的帮助。

1 个答案:

答案 0 :(得分:4)

你的功能逻辑错了。

首先,你将return()语句放在循环中,所以由于return()语句,循环总是在第一次迭代中停止。

然后,您不会创建向量pos1pos2,因此您的功能甚至无法正常工作。您没有抱怨错误的唯一原因是因为您的全球环境中可能有pos1pos2

但即使将return语句放在它应该去的地方(最后!)并创建长度为2的pos1和pos2向量,你的函数也无法工作,因为你的循环是错误的。

你循环超过1和2,除非你phrase1中的phrase2string都有2个匹配,否则根本没有意义。由于这一点,phrase2只有一个匹配,j==2 substr(text, 0, char2[j] -1)的结果是NA,其精确长度为1,因此pos2 [j]变为2同时pos1 [i]仍然是1,它符合你的条件,因此返回1

你可以这样做:

phrasedis <- function(string, phrase1, phrase2,n) { 
  char1 <- gregexpr(phrase1,string)[[1]]
  char2 <- gregexpr(phrase2,string)[[1]]

  # -1 is returned if no match was found for either phrase
  if(any(c(char1,char2) == -1)){
    return(0)
  }
  # Calculate the end positions of the words
  end1 <- char1 + attr(char1, "match.length")

  #set a to 0
  a <- 0
  # loop over all matches in char1
  for(i in seq_along(char1)){
    # Find the closest match for phrase 2
    thepos <- which.min(abs(char2 - end1[i]))
    # get all words in between.
    # Don't forget to trim white spaces before and after
    inbetween <- trimws(substring(string, end1[i], char2[thepos]-1))
    inbetween <- strsplit(inbetween,"\\s")[[1]]
    if(length(inbetween) <= n){
      a <- 1
      break
    }

  }
  return(a)
}

这是它的工作原理:

> text <- "phone rang a b cd phone rang d e f g h i no answer"

> phrasedis(text,"phone rang" , "no answer",6)
[1] 1

> text <- " There is nothing in this text"

> phrasedis(text,"phone rang" , "no answer",6)
[1] 0

> text <- "No answer but the phone rang"

> phrasedis(text,"phone rang" , "no answer",6)
[1] 0