Dataframe 需要从第二行中减去每个ID的基线值

Dataframe 需要从第二行中减去每个ID的基线值,dataframe,julia,Dataframe,Julia,我需要从每个ID的基线值中减去每个conc。我不能从每个ID的第一行减去,因为它有剂量信息。我需要req\u conc列中的值。基线值位于每个ID的第[2]行 数据帧 │ Row │ id │ time │ conc │ req_conc │ │ │ Int64 │ Int64 │ Int64? │ Int64? │ ├─────┼───────┼───────┼─────────┼──────────┤ │ 1 │ 1 │ 0 │ missing

我需要从每个ID的基线值中减去每个
conc
。我不能从每个
ID
的第一行减去,因为它有剂量信息。我需要
req\u conc
列中的值。基线值位于每个ID的第[2]行

数据帧

│ Row │ id    │ time  │ conc    │ req_conc │
│     │ Int64 │ Int64 │ Int64?  │ Int64?   │
├─────┼───────┼───────┼─────────┼──────────┤
│ 1   │ 1     │ 0     │ missing │ missing  │
│ 2   │ 1     │ 0     │ 32      │ 0        │
│ 3   │ 1     │ 1     │ 45      │ 13       │
│ 4   │ 1     │ 2     │ 36      │ 4        │
│ 5   │ 1     │ 3     │ 32      │ 0        │
│ 6   │ 2     │ 0     │ missing │ missing  │
│ 7   │ 2     │ 0     │ 40      │ 0        │
│ 8   │ 2     │ 1     │ 62      │ 22       │
│ 9   │ 2     │ 2     │ 53      │ 13       │
│ 10  │ 2     │ 3     │ 48      │ 8        │
数据

id = [1,1,1,1,1,2,2,2,2,2]
time = [0,0,1,2,3,0,0,1,2,3]
conc = [missing, 32, 45, 36, 32, missing, 40, 62, 53, 48]
req_conc = [missing, 0, 13, 4, 0, missing, 0, 22, 13, 8]

df = DataFrame(id=id, time=time, conc=conc, req_conc=req_conc)

最简单的方法是执行以下操作:

julia> transform(groupby(df, :id), :conc => (x -> x .- x[2]) => :req_conc2)
10×5 DataFrame
 Row │ id     time   conc     req_conc  req_conc2
     │ Int64  Int64  Int64?   Int64?    Int64?
─────┼────────────────────────────────────────────
   1 │     1      0  missing   missing    missing
   2 │     1      0       32         0          0
   3 │     1      1       45        13         13
   4 │     1      2       36         4          4
   5 │     1      3       32         0          0
   6 │     2      0  missing   missing    missing
   7 │     2      0       40         0          0
   8 │     2      1       62        22         22
   9 │     2      2       53        13         13
  10 │     2      3       48         8          8
在这里,我利用了这样一个事实,即在第一行中,我们有
missing
,从
missing
中减去任何值都会产生一个missing值

这假设您的数据帧是按
:id
:time
排序的,但我知道这是有保证的,对吗