Saturday, 28 September 2013

if else using the next unique value in column by key

if else using the next unique value in column by key

I have a question. How do I perform the following operations on the
sampdata object? The result that I would like to have is the sampres
object.
Thank you.
Pseudocode:
if sampdata[,flow[1] == flow[2], by = site_no]
sampdata[,flow[2]] = next unique flow value # if yes
no change # if no
Starting data:
library(data.table)
sampdata <-
data.table(c(02446500,02446500,02446500,02467000,02467000,02467000,06818000,06818000,06818000,06818000,06893000,06893000,06893000,06893000,06934500,06934500,06934500,07010000,07010000,07010000,07289000,07289000,07289000),c(21,21,22,70,76,82,14700,14700,14700,14800,11000,11000,11000,11100,19400,19400,19500,32000,32000,32100,146000,146000,147000),c(4,4.01,4.02,73.05,73.06,73.07,1,1.01,1.02,1.03,1,1.01,1.02,1.03,-1.2,-1.19,-1.18,-9.02,-9.01,-9,-4.43,-4.42,-4.41))
setnames(sampdata,c("site_no", "flow", "gage"))
setkey(sampdata, site_no)
End result:
sampres <-
data.table(c(02446500,02446500,02446500,02467000,02467000,02467000,06818000,06818000,06818000,06818000,06893000,06893000,06893000,06893000,06934500,06934500,06934500,07010000,07010000,07010000,07289000,07289000,07289000),c(21,22,22,70,76,82,14700,14800,14700,14800,11000,11100,11000,11100,19400,19500,19500,32000,32100,32100,146000,147000,147000),c(4,4.02,4.02,73.05,73.06,73.07,1,1.03,1.02,1.03,1,1.03,1.02,1.03,-1.2,-1.18,-1.18,-9.02,-9,-9,-4.43,-4.41,-4.41))
setnames(sampres,c("site_no", "flow", "gage"))
setkey(sampres, site_no)
To clarify, here are the initial data and result side-by-side, from
cbind(sampdata,sampres):
site_no flow gage site_no flow gage
1: 2446500 21 4.00 2446500 21 4.00
2: 2446500 21 4.01 2446500 22 4.02
3: 2446500 22 4.02 2446500 22 4.02
4: 2467000 70 73.05 2467000 70 73.05
5: 2467000 76 73.06 2467000 76 73.06
6: 2467000 82 73.07 2467000 82 73.07
7: 6818000 14700 1.00 6818000 14700 1.00
8: 6818000 14700 1.01 6818000 14800 1.03
9: 6818000 14700 1.02 6818000 14700 1.02
10: 6818000 14800 1.03 6818000 14800 1.03
11: 6893000 11000 1.00 6893000 11000 1.00
12: 6893000 11000 1.01 6893000 11100 1.03
13: 6893000 11000 1.02 6893000 11000 1.02
14: 6893000 11100 1.03 6893000 11100 1.03
15: 6934500 19400 -1.20 6934500 19400 -1.20
16: 6934500 19400 -1.19 6934500 19500 -1.18
17: 6934500 19500 -1.18 6934500 19500 -1.18
18: 7010000 32000 -9.02 7010000 32000 -9.02
19: 7010000 32000 -9.01 7010000 32100 -9.00
20: 7010000 32100 -9.00 7010000 32100 -9.00
21: 7289000 146000 -4.43 7289000 146000 -4.43
22: 7289000 146000 -4.42 7289000 147000 -4.41
23: 7289000 147000 -4.41 7289000 147000 -4.41
site_no flow gage site_no flow gage

No comments:

Post a Comment