Skip to content

Instantly share code, notes, and snippets.

@kevinushey
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinushey/9842100 to your computer and use it in GitHub Desktop.
Save kevinushey/9842100 to your computer and use it in GitHub Desktop.
When does `names<-` copy?
df <- data.frame(x=1)
x <- capture.output(.Internal(inspect(df)))
names(df) <- "a"
y <- capture.output(.Internal(inspect(df)))
internal_diff <- function(x, y) {
xp <- file.path( tempdir(), "Rdiff1.txt" )
yp <- file.path( tempdir(), "Rdiff2.txt" )
cat(x, file=xp, sep="\n")
cat(y, file=yp, sep="\n")
output <- c(suppressWarnings(system(paste("diff", xp, yp), intern=TRUE)))
cat(output, sep="\n")
invisible(output)
}
internal_diff(x, y)
sessionInfo()
> df <- data.frame(x=1)
> x <- capture.output(.Internal(inspect(df)))
> names(df) <- "a"
> y <- capture.output(.Internal(inspect(df)))
>
> internal_diff <- function(x, y) {
+ xp <- file.path( tempdir(), "Rdiff1.txt" )
+ yp <- file.path( tempdir(), "Rdiff2.txt" )
+ cat(x, file=xp, sep="\n")
+ cat(y, file=yp, sep="\n")
+ output <- c(suppressWarnings(system(paste("diff", xp, yp), intern=TRUE)))
+ cat(output, sep="\n")
+ invisible(output)
+ }
>
> internal_diff(x, y)
1,2c1,2
< @7ffa3b3dd0b8 19 VECSXP g0c1 [OBJ,NAM(2),ATT] (len=1, tl=0)
< @7ffa3b3dd088 14 REALSXP g0c1 [] (len=1, tl=0) 1
---
> @7ffa3dc33d98 19 VECSXP g0c1 [OBJ,NAM(1),ATT] (len=1, tl=0) ## the vector pointers are copied
> @7ffa3b3dd088 14 REALSXP g0c1 [NAM(2)] (len=1, tl=0) 1 ## the NAMED attribute is set for the data (but not copied)
4c4
< @7ffa3b3e0148 02 LISTSXP g0c0 []
---
> @7ffa3e087750 02 LISTSXP g0c0 [] ## the attributes 'pointer' is copied
6,7c6,7
< @7ffa3b3dcf08 16 STRSXP g0c1 [NAM(2)] (len=1, tl=0)
< @7ffa3b056648 09 CHARSXP g0c1 [gp=0x61] [ASCII] [cached] "x"
---
> @7ffa3dc33e28 16 STRSXP g0c1 [NAM(2)] (len=1, tl=0) ## copied STRSXP + changed CHARSXP name
> @7ffa3b82eb58 09 CHARSXP g0c1 [gp=0x61] [ASCII] [cached] "a"
9c9
< @7ffa3b3df9a8 13 INTSXP g0c1 [] (len=2, tl=0) -2147483648,-1
---
> @7ffa3b3df9a8 13 INTSXP g0c1 [NAM(2)] (len=2, tl=0) -2147483648,-1 ## just set NAM(2) to row.names
11c11
< @7ffa3b3df978 16 STRSXP g0c1 [NAM(1)] (len=1, tl=0)
---
> @7ffa3b3df978 16 STRSXP g0c1 [NAM(2)] (len=1, tl=0) ## just set NAM(2) to class
> sessionInfo()
R Under development (unstable) (2014-03-07 r65143)
Platform: x86_64-apple-darwin13.1.0 (64-bit)
locale:
[1] en_CA.UTF-8/en_CA.UTF-8/en_CA.UTF-8/C/en_CA.UTF-8/en_CA.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment