Inspired by a Stack Overflow question, here’s a way of tracking what’s been modifying the .Random.seed.
Since R makes static analysis impossible in general, the following is a runtime tracer that injects itself into the .Random.seed variable via an active binding:
NOTE: This will only work properly if called directly by the user at the top level. In particular, it won’t work inside an RMarkdown report or similar, where the top-level call is
rmarkdown::render(), orknitr::knit(), or similar; rather than, say,sample().
trace_random_seed()
sample(10)Getting .Random.seed; called from sample(10)
Setting .Random.seed; called from sample(10)
[1] 2 5 9 8 7 4 1 6 10 3The user can control whether all or only specific calls are logged …
untrace_random_seed()
trace_random_seed(ignore = sample.int)
sample(10)Getting .Random.seed; called from sample(10)
Setting .Random.seed; called from sample(10)
[1] 8 1 9 5 2 3 7 4 10 6sample.int(10) [1] 3 4 7 5 1 2 9 8 10 6… whether only to log getter or setter (default is both) …
untrace_random_seed()
trace_random_seed(what = 'setter')
sample(10)Setting .Random.seed; called from sample(10)
[1] 2 9 8 5 3 7 4 6 10 1… and, finally, the user can switch tracing off again.
untrace_random_seed()
sample(10) [1] 4 6 10 8 9 3 1 7 5 2