R语言赋值语句_R语言赋值语句<-, <<-, =有什么区别
初学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
> x #Error: object ‘x’ not found
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.<<-或->>一般用于函数内部,然后会搜索包括父层级在内的被定义的变量然后赋值.
有的时候可以用 -> 进行赋值而 = 不行
比如想复制一个式子的值给变量x
我经常先输入了一堆的式子,然后突然想起忘在前面加变量名x了
这时候用 -> x 就可以赋值了,而不用把光标移到最前面然后输入 x =
比如
sin(2*6.7)/cos(3) -> x
转载请注明:数据分析 » R语言赋值语句_R语言赋值语句<-, <<-, =有什么区别