【问题标题】:For loops giving different results on console when run within a function in R在 R 中的函数内运行时,对于在控制台上给出不同结果的循环
【发布时间】:2017-10-16 19:58:04
【问题描述】:

好的,所以我在这个函数的末尾有一个 for 循环,它应该输出在函数早期创建的生成的素数。

当我逐行运行代码时,一切正常,两个 for 循环将列表中的每个元素输出:PrimeList_p、PrimeList_q,到控制台窗口。

但是,当我通过调用函数运行代码时,for 循环仅将前 20 个左右的元素输出到控制台。为什么不打印整个列表?

require(gmp)

GenPrimes <- function(InitialSize) {
#List initialisation
PrimeList_p <<- list()
PrimeList_q <<- list()
#Loop initialisation
x <- 1
#LOOP START
while (x < 81) {
#Generate and compile prime numbers into Prime_List1.
PrimeList_p[[x]] <- nextprime(urand.bigz(size = InitialSize + x, seed = 
Sys.time()))
x <- x+1

PrimeList_q[[x]] <- nextprime(urand.bigz(size = InitialSize + x, seed = 
Sys.time()))
x <- x+1
}

#LOOP END
#Remove NULL entries in lists
PrimeList_p <<- PrimeList_p[-which(sapply(PrimeList_p, is.null))]
PrimeList_q <<- PrimeList_q[-which(sapply(PrimeList_q, is.null))]
cat("Prime p:")
for (i in 1:40){
message(PrimeList_p[[i]])
}
cat("Prime q")
for (j in 1:40){
message(PrimeList_q[[j]])
}
}

GenPrimes(1)

【问题讨论】:

    标签: r list function loops console


    【解决方案1】:

    您在一个循环中将x 增加了两次。这会在两个列表中创建 NULL 条目,这些条目由代码处理,然后保存到父环境中。然后,函数环境中仍存在 NULL 值的原始列表将传递到消息循环,这就是为什么您会在每个值之间看到一个空行的原因。将for (i in 1:40) 更改为for (i in seq_along(PrimeList_p)),这将变得很明显

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-30
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 2017-09-07
      • 2018-07-19
      相关资源
      最近更新 更多