Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement functions in R

Tags:

I read Advanced R by Hadley Wickham on his book's website. I found a question about replacement functions in R. The following result is given according to his book.

library(pryr)
x <- 1:10
address(x)
#> [1] "0x103945110"

x[2] <- 7L
address(x)
#> [1] "0x103945110"

He supposed that the address of x won't change if we just replace the second element of x. However, when I do this, the physical address of x actually changed. So, anybody tell me why?

like image 204
Travis Avatar asked Jul 02 '18 14:07

Travis


People also ask

Is there a Replace function in R?

Replacing values in a data frame is a very handy option available in R for data analysis. Using replace() in R, you can switch NA, 0, and negative values with appropriate to clear up large datasets for analysis.

How do you replace values in a column in R?

To replace a column value in R use square bracket notation df[] , By using this you can update values on a single column or on all columns. To refer to a single column use df$column_name .


1 Answers

There was a change in how R 3.5 stores values in the form a:b. If you try the same example with

library(pryr)
x <- c(1,2,3,4,5,6,7,8,9,10)
address(x)
x[2] <- 7L
address(x)

You should get the same address. Now the 1:10 isn't full expanded until it has to be. And changing an element inside the vector will cause it to expand.

like image 140
MrFlick Avatar answered Sep 28 '22 18:09

MrFlick