How to subset data table, group, and compute on j, in R

Viewed 58

I am trying to modify the column newCol from the data table dt only for the smallest year within group g1 and g2.

Here is a minimal example. As you can see, I succeeded to do what I want, but I am wondering if there is a more elegant or 'datatablish' way to do it. I only want answer in the data.table format if possible!

library(data.table)
# Dummy data
dt = data.table(year = c(2000, 2001, 2003, 2001, 2005, 2000, 2008),
    g1 = c(1, 1, 1, 2, 2, 3, 3), g2 = c(88, 88, 88, 88, 88, 54, 54))

# Set up new col to foo
dt[, newCol := "foo"]

# Correct the value for the minimal year, by group g1 and g2
dt[dt[, .I[which.min(year)], by = .(g1, g2)][, V1], newCol := "bar"]
1 Answers

We could do this in a single line with

dt[,   newCol := c("foo", "bar")[1 + (year == min(year))], .(g1, g2)]
Related