What does "x [] <- as.integer (x)" mean

When I read the R manual, I came across some lines of code as shown below (copied from the R manual for "colSums"):

 x <- cbind(x1 = 3, x2 = c(4:1, 2:5)) dimnames(x)[[1]] <- letters[1:8] x[] <- as.integer(x) 

Can someone tell me what is the purpose of the last line? Thank you

+6
source share
2 answers

I understand that assigning x[] (or assigning an object with square brackets without values ​​- for those looking for this problem) overwrites the values ​​in x , preserving the attributes that x can have, including the dimensions of the matrix. In this case, it is useful to remember that a matrix is ​​just a vector with added dimensions.

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 save the dimensions and names stored as attributes in x

 x[] <- as.integer(x) 

Until it is ...

 x <- as.integer(x) 

The same applies to vectors:

 x <- 1:10 attr(x,"blah") <- "some attribute" attributes(x) #$blah #[1] "some attribute" 

This way, it retains all your beautiful attributes:

 x[] <- 2:11 x # [1] 2 3 4 5 6 7 8 9 10 11 #attr(,"blah") #[1] "some attribute" 

While it will not:

 x <- 2:11 x #[1] 2 3 4 5 6 7 8 9 10 11 
+10
source
 x[] <- as.integer(x) 

It parses the contents of matrix x for an integer, and then saves it back to x as a matrix.

 x[,] <- as.integer(x) 

also works. But

 x <- as.integer(x) 

will lose the matrix structure.

+1
source

Source: https://habr.com/ru/post/952708/


All Articles