首页 > 解决方案 > `.Random.seed` 和 `ls()` 之间有什么关系?

问题描述

load("files.RData"); ls()打印到控制台的输出是:

'File1'   'File2'   'File3'

当这样做时(load("files.RData"))(括号的点load()是指示 R 打印该行的输出)打印到控制台的输出是:

'.Random.seed'   'File1'   'File2'   'File3'

问题:造成这种差异的原因是什么?

注意:这可能特定于 IRkernel,因为此代码正在 Jupyter 笔记本中运行。

标签: rjupyter-irkernel

解决方案


From help("ls"), we can see the purpose of the all.names argument to ls(), which has a default value of FALSE:

all.names: a logical value.  If ‘TRUE’, all object names are returned.
          If ‘FALSE’, names which begin with a ‘.’ are omitted.

So, in your first example, ls() will not print .Random.seed; it begins with a ..

Now let us consider the "Value" sections of the help files for load:

A character vector of the names of objects created, invisibly.

and Paren:

For ‘(’, the result of evaluating the argument.  This has
 visibility set, so will auto-print if used at top-level.

So, in your second example, load("files.RData") invisibly returns "A character vector of the names of objects created" (even .Random.seed), but ( auto-prints that character vector, even including .Random.seed.

What even is .Random.seed?

First, we can see what it is by looking at help(".Random.seed"):

 ‘.Random.seed’ is an integer vector, containing the random number
 generator (RNG) *state* for random number generation in R.  It can
 be saved and restored, but should not be altered by the user.

It will pop up in your global environment any time you use one of R's pseudo-random number generators. For example, in a fresh R session, I can do the following:

x <- 1
ls(all.names = TRUE)
# [1] "x"

rnorm(1)
# [1] 2.378572

ls(all.names = TRUE)
# [1] ".Random.seed" "x"           

Then I can save any or all of these R objects via save():

save(x, file = "one.RData")
save(.Random.seed, file = "two.RData")
save(x, .Random.seed, file = "all.RData")
# or, equivalently in this case,
# save(list = ls(all.names = TRUE), file = "all.RData")

If I use save.image(), everything in my global environment is saved, even files beginning with . -- according to the help file, it's a shortcut for save(list = ls(all.names = TRUE), file = ".RData", envir = .GlobalEnv).

So, wherever you got the files.RData from, they either used save.image(), or intentionally included their .Random.seed object when saving files.RData.


推荐阅读