Apr 17, 2009

R 中赋值 <-, = 的区别

目前理解,<-,=大部分地方通用,但是在函数调用时,y<-x 表示对y 赋值并将y赋给第一个参数,但是y是否进行赋值还不确定,参见下面例子。 y=x,表示函数有个参数名字叫 y,它赋值为 x 所以貌似可以全部使用=,函数调用赋值使用<- 或者 {y=x}

> f <- function(x)if(runif(1)>0.5) TRUE else x
> x<-1
> print(f(x <- x + 1))
[1] 2
> print(f(x <- x + 1))
[1] 3
> print(f(x <- x + 1))
[1] 4
> print(f(x <- x + 1))
[1] TRUE
> print(f(x <- x + 1))
[1] TRUE
> print(f(x <- x + 1))
[1] TRUE
> print(f(x <- x + 1))
[1] 5
> print(f(x = x + 1))
[1] 6
> print(f(x = x + 1))
[1] 6
> print(f(x = x + 1))
[1] 6
> print(f(x = x + 1))
[1] TRUE
> print(f(x = x + 1))
[1] 6
> print(f(x = x + 1))
[1] TRUE
> print(f(x = x + 1))
[1] 6
> print(f(x = x + 1))
[1] 6
> print(f({x = x + 1}))
[1] TRUE
> print(f({x = x + 1}))
[1] TRUE
> print(f({x = x + 1}))
[1] TRUE
> print(f({x = x + 1}))
[1] 6
> print(f({x = x + 1}))
[1] 7
> print(f({x = x + 1}))
[1] TRUE
> print(f({x = x + 1}))
[1] TRUE
> print(f({x = x + 1}))
[1] 8
>

0 comments: