Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does appending to a list in R result in copying?

Tags:

Suppose I have create a list in R and append to it as follows:

x = list(10) x[[2]] = 20 

Is this equivalent to

x = list(10) x = list(10, 20) 

? I'm not so experienced with the particular details of how R handles lists in memory, but my limited understanding is that it tends to be copy-happy; what would be ideal for me would be that the first option doesn't involve essentially creating another list in memory, but just results in setting aside a new place in memory for the appended value. Essentially, if I have a big list, I don't want R to make another copy of it if I just want to append something to it.

If the behaviour I want is not what is given here, is there any other way I can get the desired effect?

like image 651
guy Avatar asked Oct 07 '12 20:10

guy


People also ask

Does list append make a copy?

💡 Tips: When you use . append() the original list is modified. The method does not create a copy of the list – it mutates the original list in memory.

Can you append to a list in R?

To append an element in the R List, use the append() function. You can use the concatenate approach to add components to a list. While concatenate does a great job of adding elements to the R list, the append() function operates faster.

How do I add an item to a list in R?

To add an item to a list in R programming, call append() function and pass the list and item as arguments in the function call.


1 Answers

I'm fairly confident the answer is "no". I used the following code to double check:

Rprof(tmp <- tempfile(), memory.profiling = TRUE)  x <- list() for (i in 1:100) x[[i]] <- runif(10000)  Rprof() summaryRprof(tmp, memory = "stats") unlink(tmp) 

The output:

# index: runif #      vsize.small  max.vsize.small      vsize.large  max.vsize.large  #            76411           381781           424523          1504387  #            nodes        max.nodes     duplications tot.duplications  #          2725878         13583136                0                0  #          samples  #                5  

The relevant part being duplications = 0.

like image 136
flodel Avatar answered Sep 22 '22 17:09

flodel