首页 > 解决方案 > 如何在带有向量的函数中使用条件和停止函数

问题描述

我有一个函数可以根据随机整数 x 移动单词中的字母。我需要在开始时设置一个条件,如果 x>list,函数将停止。我尝试使用停止功能,但它产生了错误。

Error in .f(.x[[i]], ...) : argument "x" is missing, with no default

图书馆(咕噜)

wordlist <- c("Is", "Book", "Appreciate", "Cherry", "Computer", "Of")

shift <- function(list, x){
  x <- sample(1:4,6, replace==TRUE)
  if (x>list) stop("length of x is greater than the letters in the word!")
  paste0(substr(list,nchar(list)-x+1,nchar(list)), substr(list,1,nchar(list)-x))
}

map(wordlist, shift)

例如,对于前两个单词“Of”和“Book”,假设“Of”为 x=3,“Book”为 x=2,它将产生以下输出:

[[1]]
[[1]]$result
NULL
[[1]]$error
<simpleError in .f(...): length of x is greater than the letters in the word!>

[[2]]
[[2]]$result
[1] "okbo"
[[2]]$error
NULL

标签: rif-statementconditional-statementspurrr

解决方案


推荐阅读