【问题标题】:Repeating two loops in R until a condtion is met in R在 R 中重复两个循环,直到在 R 中满足条件
【发布时间】:2014-05-12 03:39:35
【问题描述】:

我试图多次重复两个循环,直到满足条件

第一个循环是从字符串中删除关键字(模式)的第一个实例。 第二个循环是统计同一字符串中关键字的实例数。

数据位于具有 3 列的数据框中 - 字符串、关键字和关键字在字符串中重复的次数(NoKW)

string <- c (" temple san temple lush ", " mohito sudoku war ", " martyr  martyr metal martyr", " jump statement statement ", " window capsule turn ")
keyword <- c (" temple ", " sudoku ", " martyr " , " statement ", " capsule ")
NoKW <- c(2,1,3,2,1)
data <- data.frame (string, keyword, NoKW)
data$string <- as.character(data$string)
data$keyword <- as.character(data$keyword)

这个想法是顺序删除关键字的实例,直到我在相应的字符串中只有一个关键字实例。

我尝试如下使用重复。

repeat
{
M <- nrow(data);
for (j in 1:M){
if(1 < data[j,3]) data[j,1] <- str_replace(data[j,1], data[j,2], " ")
};
for (i in 1:M){
data[i,3] <- sum(str_count(data[i,1], data[i,2]))
};
max <- as.numeric(max(data$NoKW));
if (max = 1)
break;
}

但它给出了以下错误

Error: unexpected '=' in:
"    };
if (max ="
>         break;
Error: no loop for break/next, jumping to top level
> }
Error: unexpected '}' in "}"
>

我是 R 循环的新手,所以你能告诉我哪里出错了。

【问题讨论】:

  • 不应该是if(max == 1)
  • 我觉得你需要:if (max == 1)
  • 首先,您是在比较与分配,所以在最后的if 声明中,===。第二:分号:只要说no(这不是javascript :-)。第三,SO R Wiki stackoverflow.com/tags/r/info 有大量很好的介绍资源,可以帮助您学习良好的 R 实践(并更加熟悉该语言)。

标签: string r for-loop repeat


【解决方案1】:

这个想法是顺序删除关键字的实例,直到我有 对应字符串中只有一个关键字实例。

您不需要for 循环:

#split your strings by space
substrings <- strsplit(string, " ", fixed=TRUE)

#remove spaces from keywords
keyword_clean <- gsub("\\s", "", keyword)

#loop over the strings
sapply(substrings, function(s) {
  #which word is duplicated and a keyword
  rm <- which(duplicated(s, fromLast=TRUE) & s %in% keyword_clean)  
  #remove the duplicated keywords
  if (length(rm > 0)) s <- s[-rm]
  #paste words together
  paste(s, collapse=" ")
  })

#[1] " san temple lush"     " mohito sudoku war"   "  metal martyr"       " jump statement"      " window capsule turn"

【讨论】:

    猜你喜欢
    • 2018-11-09
    • 2018-12-24
    • 1970-01-01
    • 2013-12-28
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 2018-09-09
    相关资源
    最近更新 更多