在R中分配数据帧时使用'='与'<-'运算符的不同行为 [英] Different behavior in using '=' versus '<-' operator while assigning a dataframe in R
问题描述
我想知道为什么在分配dataframe
时使用=
和<-
会有区别.
I would like to know why there is a difference between using =
and <-
while assigning a dataframe
.
情况a:使用=
set.seed(100);a <- data.frame(a1=rnorm(10),a2=sample(c(1,0),10,replace=TRUE))
案例b:使用<-
set.seed(100);b <- data.frame(b1 <- rnorm(10),b2 <- sample(c(1,0),10,replace=TRUE))
为什么有以下区别?为什么第二种方法不保留变量/列名?
Why is there the following difference? Why does not second method retain the variable/column names?
> a
a1 a2
1 -0.50219235 0
2 0.13153117 0
3 -0.07891709 1
4 0.88678481 1
5 0.11697127 0
>b
b1....rnorm.5. b2....sample.c.1..0...5..replace...TRUE.
1 -0.50219235 0
2 0.13153117 0
3 -0.07891709 1
4 0.88678481 1
5 0.11697127 0
推荐答案
在函数内部,'='用作命名或将函数引用到具有特定名称的变量,而<-则是分配函数.当R运行时,它将首先在您的函数参数中解析'<-'函数,然后将在等号或全表达式左侧的东西处命名变量,在这种情况下为"b1 <-rnorm(10) .最后它将解析该功能(在本例中为data.frame).
Within functions '=' is used as naming or referring the function to a variable of a particular name and <- refers to the assignment function. When R runs it will first resolve '<-" functions within your function parameters. It will then name the variable wither the thing to the left of the equal sign or the full expression in this case "b1 <- rnorm(10)". Finally it will resolve the function (in this case data.frame).
您几乎总是想在函数中使用'='.在某些情况下,您可能希望嵌套一个赋值<-",但这通常会使您的代码难以理解.
You almost always want to use the '=' within a function. There can be cases where you may want to nest an assignment "<-" but normally this will make your code ridiculous to read.
这篇关于在R中分配数据帧时使用'='与'<-'运算符的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!