Reputation: 1607
I have been following a tutorial on data.tables here Let's say that I have the following table (I have changed the original table to fit my question)
## gear cyl gearsL
## 1: 4 6 4,3,5
## 2: 4 6 4,3,5
## 3: 4 4 4,3,5
## 4: 3 6 5,6,7
## 5: 3 8 5,6,7
## 6: 3 6 5,6,7
I now want to create a new column which will "ungroup" the gearsL column, as follows:
## gear cyl gearsL gearA
## 1: 4 6 4,3,5 4
## 2: 4 6 4,3,5 3
## 3: 4 4 4,3,5 5
## 4: 3 6 5,6,7 5
## 5: 3 8 5,6,7 6
## 6: 3 6 5,6,7 7
I can use the following snippet of code to extract a static element, e.g. element at index 2.
dt[,gearL1:=lapply(gearsL, function(x) x[2])]
dt[,gearS1:=sapply(gearsL, function(x) x[2])]
This will result in the following table:
## gear cyl gearsL gearL1 gearS1
## 1: 4 6 4,3,5 3 3
## 2: 4 6 4,3,5 3 3
## 3: 4 4 4,3,5 3 3
## 4: 3 6 5,6,7 6 6
## 5: 3 8 5,6,7 6 6
## 6: 3 6 5,6,7 6 6
However, I want a "dynamic" index. First, I created a new field, called IDX, which acts as a row-number with groups.
dt[,IDX:=1:.N,by='gear']
which will result in the following table:
## gear cyl gearsL gearL1 gearS1 IDX
## 1: 4 6 4,3,5 3 3 1
## 2: 4 6 4,3,5 3 3 2
## 3: 4 4 4,3,5 3 3 3
## 4: 3 6 5,6,7 6 6 1
## 5: 3 8 5,6,7 6 6 2
## 6: 3 6 5,6,7 6 6 3
Using the newly created IDX column, I would like to access the elements of each list as follows:
dt[,gearA:=sapply(gearsL, function(x) x[IDX])]
dt[,gearA:=lapply(gearsL, function(x) x[IDX])]
However, the above snippet doesn't work as expected. How can I access the elements of a list based on the value of another column?
Upvotes: 1
Views: 2716
Reputation: 5263
dt[, gearA := mapply('[[', gearsL, IDX, SIMPLIFY = TRUE)]
This runs along both gearsL
and IDX
, giving them as arguments to the [[
function. I.e., gears[[i]][[IDX[[i]]]]
.
Upvotes: 2