Ricky
Ricky

Reputation: 2750

Replace all occurrences

I have a below data frame

x=c(1:21)
y=c(rep(0,2),rep(3,7),rep(1,12))
z=c(rep(1,17),rep(3,4))
table=data.table(x,y,z)

In this I need to replace all the 3's in the column y with the value of y where z value is 3 (which is 1 in this case).

table[, N := .N, rleid(y)]
table[, y := replace(y, N ==1, NA)]
table[N==1, y := zoo::na.locf(y)][, N := NULL]

I tried with this but this one only replaces one occurrence not all .Any help is appreciated.

Upvotes: 1

Views: 56

Answers (2)

akrun
akrun

Reputation: 887991

We can use fifelse from data.table

library(data.table)
table[, y := fifelse(y == 3, y[z==3][1], y)]

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389355

We can replace all y values where y is 3 with the first occurrence of y value where z is 3.

library(data.table)
table[, y := replace(y, y == 3, y[z==3][1])]
#Or similarly,
#table[, y := replace(y, y == 3, y[which.max(z==3)])]

Upvotes: 0

Related Questions