Gauss.Y Gauss.Y - 3 months ago 12
R Question

How to change one variable at the nth occurrence of a second variable?

There is a data.table

library(data.table)
car <- data.table(no = 1:100, turn = sample(1:5,100,replace = TRUE),
dis = sample(1:10,100,replace = TRUE))


I want to change "dis" to -1, at the nth occurrence of
turn == 3
, say the third.

I can select the third row of
turn == 3
:

car[turn == 3, .SD[3]]


However, I don't manage to update "dis" at this row:

car[turn == 3, .SD[3]][, dis := -1]


A related Q&A: Conditionally replacing column values with data.table.

Answer Source

Some alternatives. Use rowid or cumsum to create a counter of rows within groups*. Add the counter to your condition in i.

A slightly smaller toy data set, to make it easier to track the changes:

d <- data.table(x = 1:3, y = 1:12)

d[rowid(x) == 3 & x == 3, y := -1]

# @mt1022
d[cumsum(x == 3) == 3 & (x == 3), y := -1]

# @docendo discimus
d[(ix <- x == 3) & cumsum(ix) == 3, y := -1]


Numbering rows within groups in a data frame