# R语言赋值语句_R语言赋值语句<-, <<-, =有什么区别

502℃

R语言赋值语句_R语言赋值语句<-, <<-, =有什么区别

> matrix(1:20,ncol<-4)
[,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20
> ncol
[1] 4

matrix(1:20, ncol <- 4) 与 matrix(1:20, 4) 是等同的，也就是 matrix(1:20, nrow = 4)

What’s the difference?

The main difference between the two assignment operators is scope. It’s easiest to see the difference with an example:

##Delete x (if it exists)
> rm(x)
> mean(x=1:10) #[1] 5.5

Here x is declared within the function’s scope of the function, so it doesn’t exist in the user workspace. Now, let’s run the same piece of code with using the <- operator:

> mean(x <- 1:10)# [1] 5.5
> x # [1] 1 2 3 4 5 6 7 8 9 10

This time the x variable is declared within the user workspace.

When does the assignment take place?

In the code above, you may be tempted to thing that we “assign 1:10 to x, then calculate the mean.” This would be true for languages such as C, but it isn’t true in R. Consider the following function:

> a <- 1
> f <- function(a) return(TRUE)
> f <- f(a <- a + 1); a
[1] TRUE
[1] 1

Notice that the value of a hasn’t changed! In R, the value of a will only change if we need to evaluate the argument in the function. This can lead to unpredictable behaviour:

> f <- function(a) if(runif(1)>0.5) TRUE else a
> f(a <- a+1);a
[1] 2
> f(a <- a+1);a
[1] TRUE
[1] 2
> f(a <- a+1);a
[1] 3

1.<-或->可赋值到当前操作的环境里的变量
2.<<-或->>一般用于函数内部,然后会搜索包括父层级在内的被定义的变量然后赋值.

sin(2*6.7)/cos(3) -> x

• 在线沟通，请点我在线咨询

• 咨询热线：
000-000-0000
客服qq：
3285157825