简体   繁体   English

“x [] < - as.integer(x)”是什么意思“

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

When I read R manual, I encountered some lines of code as below(copied from R manual for 'colSums'): 当我阅读R手册时,我遇到了一些代码行如下(从R手册复制'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. 我的理解是分配给x[] (或分配给带有方括号的对象,没有值 - 对于那些搜索此问题的人来说)会覆盖x的值,同时保留x可能具有的attributes ,包括矩阵维度。 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属性

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)

It parses the contents of matrix x into integer, then stores it back into x, as a matrix. 它将matrix x的内容解析为整数,然后将其作为矩阵存储回x。

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

also works. 也有效。 But

x <- as.integer(x)

will lose the matrix structure. 将失去矩阵结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM