Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the meaning of "x[] <- as.integer(x)"

Tags:

r

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!

like image 758
Gao Hao Avatar asked Aug 29 '13 03:08

Gao Hao


1 Answers

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
like image 56
thelatemail Avatar answered Sep 17 '22 23:09

thelatemail