我需要从每个 ID 的基线值中减去每个 conc
。我无法从每个 ID 的第一行中减去,因为它有剂量信息。我需要 req_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
中减去任何内容都会产生一个缺失值。
这假设您的数据框按 :id
和 :time
排序,但我知道这是有保证的 - 对吗?
关于dataframe - 需要从第二行中减去作为每个 ID 的基线值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65472601/