对于在R中的函数内运行时在控制台上给出不同结果的循环

时间:2017-10-16 19:58:04

标签: r list function loops console

Hokay,所以我在这个函数的末尾有一个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)

1 个答案:

答案 0 :(得分:0)

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