5

I have the following scenario, I first create a data table as shown below

x = data.table(f1 = c('a','b','c','d'))
x = x[,rn := .I]

This yields

> x
   f1 rn
1:  a  1
2:  b  2
3:  c  3
4:  d  4
>

Where rn is simply the row number. Now, I have another data.table y as

y = data.table(f2=c('b','c','f'))

What I would like to be able to do is for elements in y that are in x, I want to subtract 2 from the corresponding values in rn. So the expected data.table is

x
   f1 rn
1: a  1
2: b  0
3: c  1
4: d  4

How does one get to this? x[y] and y[x] don't help at all as they just do joins.

4

2 回答 2

6

您可以按所需行使用%chin%ini子集x,然后运行您的j表达式...

x[ f1 %chin% y$f2 , rn := rn - 2L ]
x
#   f1 rn
#1:  a  1
#2:  b  0
#3:  c  1
#4:  d  4

%chin%%in%运算符的快速版本,专门用于data.table. 注意2应该是2L指定一个类型,否则你会得到一个警告(如果你正在处理数据类型"integer",显然不要使用这个)。"numeric"

于 2013-11-07T23:34:30.273 回答
5

如果您的数据是键控的,您可以使用如下连接:

setkey(x, f1)
x[y, rn := rn - 2L]
x
#   f1 rn
#1:  a  1
#2:  b  0
#3:  c  1
#4:  d  4
于 2013-11-07T23:58:24.313 回答