简体   繁体   English

R:关于LHS和RHS的分配和操作顺序的混淆

[英]R : confusion regarding LHS and RHS of assignment and order of operation

I am having some fundamental confusion with R. I have a snippet of R code. 我对R有一些基本的困惑。我有一段R代码。

> m <- 1:10
> m
 [1]  1  2  3  4  5  6  7  8  9 10
> dim(m) <- c(2,5)
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10

Now I am a C/Python programmer and the line dim(m) <- c(2,5) is incredibly confusing to me. 现在我是一名C / Python程序员,行dim(m) <- c(2,5)让我感到非常困惑。 I realize that it effectively changed a vector into a matrix, however looking at it I do not understand the logic/order of operation. 我意识到它有效地将矢量变成了矩阵,但是看着它我不理解逻辑/操作顺序。

<- is the assignment operator in R. So to me, logically the order of operation is : assign (2,5) to the output of dim(m). <-是R中的赋值运算符。所以对我来说,逻辑上操作的顺序是:将(2,5)分配给dim(m)的输出。 Since the output of dim(m) isn't assigned to a variable, the output would be lost. 由于dim(m)的输出未分配给变量,因此输出将丢失。

Could someone explain how I should read the line dim(m) <- c(2,5) ? 有人可以解释我应该如何读取线条dim(m) <- c(2,5) What is the order of operation? 操作顺序是什么? It seems that the order of operation using <- to changes depending on the LHS and RHS of the equation. 似乎使用<-的操作顺序根据等式的LHS RHS而变化。

These are special functions called Replacement Functions. 这些是称为替换函数的特殊函数。 I quote from Hadley's Advanced-R book: 我引用Hadley的Advanced-R书:

Replacement functions act like they modify their arguments in place, and have the special name xxx<-. 替换函数就像它们修改它们的参数一样,并且具有特殊名称xxx < - 。 They typically have two arguments (x and value), although they can have more, and they must return the modified object. 它们通常有两个参数(x和value),虽然它们可以有更多,但它们必须返回修改后的对象。 For example, the following function allows you to modify the second element of a vector: 例如,以下函数允许您修改向量的第二个元素:

`second<-` <- function(x, value) {
  x[2] <- value
  x
}
x <- 1:10
second(x) <- 5L
x
#>  [1]  1  5  3  4  5  6  7  8  9 10

When R evaluates the assignment second(x) <- 5, it notices that the left hand side of the <- is not a simple name, so it looks for a function named second<- to do the replacement. 当R计算赋值second(x)< - 5时,它注意到< - 的左侧不是简单名称,因此它查找名为second < - 的函数来进行替换。

You can check the full chapter here under the Replacement Functions title. 您可以查看完整的章节这里下的替代函数称号。

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

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