Guest User

Untitled

a guest
Aug 20th, 2019
86
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. library(data.table)
  2. dat <- data.table(id=1:10, group=rep(1:2, each=5), x=rnorm(10))
  3.  
  4. > dat
  5. id group x
  6. 1: 1 1 -0.39384959
  7. 2: 2 1 -0.03081369
  8. 3: 3 1 -1.30571673
  9. 4: 4 1 -1.82379155
  10. 5: 5 1 2.36751011
  11. 6: 6 2 0.21523454
  12. 7: 7 2 -0.18905780
  13. 8: 8 2 1.80707868
  14. 9: 9 2 0.88348164
  15. 10: 10 2 0.38374826
  16.  
  17. library(data.table)
  18. dat[, x := replace(x,seq_len(.N)==.N,0) ,by=group]
  19.  
  20. dat
  21. # id group x
  22. # 1: 1 1 -0.3148360
  23. # 2: 2 1 -0.1737918
  24. # 3: 3 1 -0.6768283
  25. # 4: 4 1 0.4066397
  26. # 5: 5 1 0.0000000
  27. # 6: 6 2 -0.3606155
  28. # 7: 7 2 0.1965135
  29. # 8: 8 2 0.1488247
  30. # 9: 9 2 -1.8684589
  31. #10: 10 2 0.0000000
  32.  
  33. dat[, x := ifelse(seq_along(x) == .N, 0, x), group][]
  34.  
  35. # id group x
  36. # 1: 1 1 -0.39593612
  37. # 2: 2 1 -0.16050994
  38. # 3: 3 1 0.27635653
  39. # 4: 4 1 -1.13830591
  40. # 5: 5 1 0.00000000
  41. # 6: 6 2 -0.50796065
  42. # 7: 7 2 -2.08919586
  43. # 8: 8 2 1.02132570
  44. # 9: 9 2 0.05813759
  45. # 10: 10 2 0.00000000
  46.  
  47. dat[, x := replace(x, x == last(x), 0), by = group]
  48.  
  49. id group x
  50. 1: 1 1 0.1456084
  51. 2: 2 1 1.1704387
  52. 3: 3 1 0.5015786
  53. 4: 4 1 0.1095455
  54. 5: 5 1 0.0000000
  55. 6: 6 2 0.5186358
  56. 7: 7 2 0.8648612
  57. 8: 8 2 -0.5993376
  58. 9: 9 2 -0.2663061
  59. 10: 10 2 0.0000000
RAW Paste Data