R自我参考 [英] R self reference
问题描述
在RI发现自己在做这样的事情很多:
In R I find myself doing something like this a lot:
adataframe [adataframe $ col == something ]< - dataframe [adataframe $ col == something]] + 1
漫长而乏味有一些方法我
引用我正在改变的对象,如
This way is kind of long and tedious. Is there some way for me
to reference the object I am trying to change such as
adataframe[adataframe$col==something]<-$self+1
?
推荐答案
尝试打包数据.table 及其:=
运算符。它非常快,很短。
Try package data.table and its :=
operator. It's very fast and very short.
DT[col1==something, col2:=col3+1]
第一部分 col1 == something
是该子集。你可以把任何东西放在这里,并使用列名,就像它们是变量一样;即不需要使用 $
。然后第二部分 col2:= col3 + 1
将RHS分配给该子集内的LHS,其中可以将列名分配为如同变量一样。 :=
通过引用分配。没有任何对象的副本被采取,所以比 < - $ / code>,
=
,在
和转换
。
The first part col1==something
is the subset. You can put anything here and use the column names as if they are variables; i.e., no need to use $
. Then the second part col2:=col3+1
assigns the RHS to the LHS within that subset, where the column names can be assigned to as if they are variables. :=
is assignment by reference. No copies of any object are taken, so is faster than <-
, =
, within
and transform
.
此外,即将在v1.8.1中实现, j
的语法的最终目标是允许 j $ c $中的
:=
c>像这样将它与相结合
,请参阅问题:何时应该在data.table中使用:=
运算符。
Also, soon to be implemented in v1.8.1, one end goal of j
's syntax allowing :=
in j
like that is combining it with by
, see question: when should I use the :=
operator in data.table.
UDPDATE:在2012年7月,确实发布了(:=
。
UDPDATE : That was indeed released (:=
by group) in July 2012.
这篇关于R自我参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!