Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(data.table)
- dat <- data.table(id=1:10, group=rep(1:2, each=5), x=rnorm(10))
- > dat
- id group x
- 1: 1 1 -0.39384959
- 2: 2 1 -0.03081369
- 3: 3 1 -1.30571673
- 4: 4 1 -1.82379155
- 5: 5 1 2.36751011
- 6: 6 2 0.21523454
- 7: 7 2 -0.18905780
- 8: 8 2 1.80707868
- 9: 9 2 0.88348164
- 10: 10 2 0.38374826
- library(data.table)
- dat[, x := replace(x,seq_len(.N)==.N,0) ,by=group]
- dat
- # id group x
- # 1: 1 1 -0.3148360
- # 2: 2 1 -0.1737918
- # 3: 3 1 -0.6768283
- # 4: 4 1 0.4066397
- # 5: 5 1 0.0000000
- # 6: 6 2 -0.3606155
- # 7: 7 2 0.1965135
- # 8: 8 2 0.1488247
- # 9: 9 2 -1.8684589
- #10: 10 2 0.0000000
- dat[, x := ifelse(seq_along(x) == .N, 0, x), group][]
- # id group x
- # 1: 1 1 -0.39593612
- # 2: 2 1 -0.16050994
- # 3: 3 1 0.27635653
- # 4: 4 1 -1.13830591
- # 5: 5 1 0.00000000
- # 6: 6 2 -0.50796065
- # 7: 7 2 -2.08919586
- # 8: 8 2 1.02132570
- # 9: 9 2 0.05813759
- # 10: 10 2 0.00000000
- dat[, x := replace(x, x == last(x), 0), by = group]
- id group x
- 1: 1 1 0.1456084
- 2: 2 1 1.1704387
- 3: 3 1 0.5015786
- 4: 4 1 0.1095455
- 5: 5 1 0.0000000
- 6: 6 2 0.5186358
- 7: 7 2 0.8648612
- 8: 8 2 -0.5993376
- 9: 9 2 -0.2663061
- 10: 10 2 0.0000000
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement