Julian - 1 year ago 47

R Question

I have the following data.table:

`dat<-data.table(Y=as.factor(c("a","b","a")),"a"=c(1,2,3),"b"=c(3,2,1))`

It looks like:

`Y a b`

1: a 1 3

2: b 2 2

3: a 3 1

What I want is to subtract the value of the column indicated by the value of Y by 1. E.g. the Y value of the first row is "a", so the value of the column "a" in the first row should be reduced by one.

The result should be:

`Y a b`

1: a 0 3

2: b 2 1

3: a 2 1

Is this possible? If yes, how? Thank you!

Answer Source

Using self-joins and `get`

:

```
for (yval in dat[ , unique(Y)]){
dat[yval, (yval) := get(yval) - 1L, on = "Y"]
}
dat[]
# Y a b
# 1: a 0 3
# 2: b 2 1
# 3: a 2 1
```

Apparently this requires the development version (1.9.7+). Can't think of what the update was...

To install, follow instructions here.

To make this work on 1.9.6, do:

```
setkey(dat, Y)
for (yval in dat[ , unique(Y)]){
dat[yval, (yval) := get(yval) - 1L]
}
dat[]
```