当我阅读 R 手册时,我遇到了如下几行代码(从 R 手册中复制“colSums”):
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8]
x[] <- as.integer(x)
有人能告诉我最后一行的目的是什么吗?谢谢!
当我阅读 R 手册时,我遇到了如下几行代码(从 R 手册中复制“colSums”):
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8]
x[] <- as.integer(x)
有人能告诉我最后一行的目的是什么吗?谢谢!
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
x[] <- as.integer(x)
它将 的内容解析matrix x
为整数,然后将其作为矩阵存储回 x 中。
x[,] <- as.integer(x)
也有效。但
x <- as.integer(x)
将失去矩阵结构。