我应该使用什么而不是R中的pass-by-reference?

时间:2021-05-05 07:11:16

I wrote a function in R that, if I could pass by reference, would work as I intend. It involves nesting sapply calls and performing assignment inside them. Since R does not use pass by reference, the functions don't work.

我在R中编写了一个函数,如果我可以通过引用传递,它将按照我的意图工作。它涉及嵌套sapply调用并在其中执行赋值。由于R不使用传递引用,因此这些函数不起作用。

I am aware that there are packages available such as R.oo to bring pass by reference-y aspects to R, but I would like to learn if there is a better way. What is the 'R' way of passing data if pass by reference is not available?

我知道有一些可用的软件包,例如R.oo,可以通过引用y方面传递给R,但我想知道是否有更好的方法。如果无法通过引用传递数据,那么传递数据的'R'方式是什么?

1 个解决方案

#1


1  

If you don't modify an argument then it won't actually copy it so it may be pointless to do anything special:

如果你不修改一个参数,那么它实际上不会复制它,所以做一些特别的事情可能毫无意义:

> gc() # using 6.2 MB of Vcells
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 560642 15.0     984024 26.3   984024 26.3
Vcells 809878  6.2    2670432 20.4  2310055 17.7
> x <- as.numeric(1:1000000)
> gc() # now we are using 13.9 MB
          used (Mb) gc trigger (Mb) max used (Mb)
Ncells  560640 15.0     984024 26.3   984024 26.3
Vcells 1809867 13.9    2883953 22.1  2310055 17.7
> f0 <- function(x) { s <- sum(x); print(gc()); s }
> f0(x) # f0 did not use appreciably more despite using a huge vector
          used (Mb) gc trigger (Mb) max used (Mb)
Ncells  560655 15.0     984024 26.3   984024 26.3
Vcells 1809872 13.9    2883953 22.1  2310055 17.7
[1] 500000500000

EDIT: minor changes to example

编辑:对示例进行细微更改

#1


1  

If you don't modify an argument then it won't actually copy it so it may be pointless to do anything special:

如果你不修改一个参数,那么它实际上不会复制它,所以做一些特别的事情可能毫无意义:

> gc() # using 6.2 MB of Vcells
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 560642 15.0     984024 26.3   984024 26.3
Vcells 809878  6.2    2670432 20.4  2310055 17.7
> x <- as.numeric(1:1000000)
> gc() # now we are using 13.9 MB
          used (Mb) gc trigger (Mb) max used (Mb)
Ncells  560640 15.0     984024 26.3   984024 26.3
Vcells 1809867 13.9    2883953 22.1  2310055 17.7
> f0 <- function(x) { s <- sum(x); print(gc()); s }
> f0(x) # f0 did not use appreciably more despite using a huge vector
          used (Mb) gc trigger (Mb) max used (Mb)
Ncells  560655 15.0     984024 26.3   984024 26.3
Vcells 1809872 13.9    2883953 22.1  2310055 17.7
[1] 500000500000

EDIT: minor changes to example

编辑:对示例进行细微更改