When I read R manual, I encountered some lines of code as below(copied from R manual for 'colSums'):
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8]
x[] <- as.integer(x)
Could someone tell me what the purpose of the last line is? Thanks!
My understanding is that assigning to x[]
(or assigning to an object with square brackets, with no values - for those searching for this issue) overwrites the values in x
, while keeping the attributes
that x
may have, including matrix dimensions. In this case, it is helpful to remember that a matrix is pretty much just a vector with dimensions added.
So given...
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8]
attributes(x)
#$dim
#[1] 8 2
#
#$dimnames
#$dimnames[[1]]
#[1] "a" "b" "c" "d" "e" "f" "g" "h"
#
#$dimnames[[2]]
#[1] "x1" "x2"
...this will keep the dimensions and names stored as attributes in x
x[] <- as.integer(x)
While this won't...
x <- as.integer(x)
The same logic applies to vectors too:
x <- 1:10
attr(x,"blah") <- "some attribute"
attributes(x)
#$blah
#[1] "some attribute"
So this keeps all your lovely attributes:
x[] <- 2:11
x
# [1] 2 3 4 5 6 7 8 9 10 11
#attr(,"blah")
#[1] "some attribute"
Whereas this won't:
x <- 2:11
x
#[1] 2 3 4 5 6 7 8 9 10 11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With