【问题标题】:Go back to the beginning of a loop in R?回到 R 中循环的开头?
【发布时间】:2020-06-26 14:02:10
【问题描述】:

我目前有一个 for 循环,它将遍历以单词分隔的段落列表,psw_list,随机选择一个单词段落,然后将该单词更改为另一个相同的词性。你会注意到底部的 else 语句是空白的,因为如果词性是列出的任何一个,我希望它回到 if 语句的开头,但我不确定如何,有什么想法吗?对不起,如果代码 sn-p 很长。

for (i in iterations){ # for a specific change in the total amount of changes
  n <- sample(names(psw_list), 1) 
  j <- sample(length(psw_list[[n]]), 1) 
  parsed <- spacy_parse(psw_list[[n]][j])
  pos <- parsed[1,6]
    # tabbing because the if starts here
  if (pos == "NOUN"){
    sample(nouns, 1) -> replacement
    as.character(replacement) -> replacement
    psw_list[[n]][j] <- replacement
  } else if (pos == "ADJ"){
    sample(adjs, 1) -> replacement
    as.character(replacement) -> replacement
    psw_list[[n]][j] <- replacement
  } else if (pos == "ADV"){
    sample(adverbs, 1) -> replacement
    as.character(replacement) -> replacement
    psw_list[[n]][j] <- replacement
  } else if (pos == "PROPN"){
    sample(proper_nouns, 1) -> replacement
    as.character(replacement) -> replacement
    psw_list[[n]][j] <- replacement
  } else if (pos == "ADP"){
    sample(prepositions, 1) -> replacement
    as.character(replacement) -> replacement
    psw_list[[n]][j] <- replacement
  } else if (pos == "VERB"){
    # Need to add nested if to determine if it's past or present tense
    sample(verbs_past, 1) -> replacement
    as.character(replacement) -> replacement
    psw_list[[n]][j] <- replacement
  } else if( word.pos == "AUX" || "CONJ" || "DET" || "INTJ" || "NUM" || "PART" || "PROPN" || "PUNCT" 
             || "SCONJ" || "SYM" || "X") {
   
  }
}

【问题讨论】:

  • 您不能将索引变量(在您的情况下为 i)重置为您想要的位置(所以无论迭代的第一个值是什么)?
  • @nilesguo 迭代是用户定义的变量,所以我真的不想这样做
  • @nilesguo 这甚至行不通,即使 OP 愿意这样做。我认为stackoverflow.com/a/42983545/8386140 对你们俩都有启发。 @djc1223,您可能需要与 for 循环不同的流量控制设置,可能是 while 循环,如链接答案中所示

标签: r for-loop if-statement


【解决方案1】:

似乎您应该避免继续而不是尝试“返回”。在选择单词的前几行周围嵌套一个重复循环,直到找到已处理的单词

for (i in iterations){ # for a specific change in the total amount of changes

  repeat{

    n <- sample(names(psw_list), 1) 
    j <- sample(length(psw_list[[n]]), 1) 
    parsed <- spacy_parse(psw_list[[n]][j])
    pos <- parsed[1,6]
  
    if(pos %in% LIST_OF_ACCEPTABLE_POS) break;

  }

...rest of for loop...

}

``

【讨论】:

  • 我已经玩了一段时间了,我意识到 break 语句会破坏整个循环,它不会将其发送回开头,有什么想法吗?
  • 在某些时候你需要break 来获得repeat 循环(否则它将是一个无限循环。话虽如此,听起来你正在寻找next命令
猜你喜欢
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多