私はこのデータを持っています。これをAと名付けました。
A <- read.table(text = "ID TIME EVID AMT DOSE
1 10 1 100 20
1 12 1 100 20
1 14 1 100 20
1 16 1 100 20
1 17 0 100 20
1 18 1 100 20
1 20 1 100 20
1 22 1 100 20
2 5 1 100 40
2 10 1 100 40
2 15 1 100 40
2 17 0 100 40
2 20 1 100 40
3 4 1 100 25
3 7 1 100 25
3 10 1 100 25
3 11 0 100 25
3 13 1 100 25
3 16 1 100 25
3 19 1 100 25", header = TRUE)
そして、私の目標は、EVID = 2、前の行IDと同じID、およびTIME=前の行のTIMEエントリにAMT/ DOSEを加えた新しい行を挿入することです。新しい行は、最初のEVID=1の後に続くようにします。 0s、以下のように:
ID TIME EVID AMT DOSE
1 10 1 100 20
1 12 1 100 20
1 14 1 100 20
1 16 1 100 20
1 17 0 100 20
1 18 1 100 20
1 23 2 100 20
1 20 1 100 20
1 22 1 100 20
2 5 1 100 40
2 10 1 100 40
2 15 1 100 40
2 17 0 100 40
2 20 1 100 40
2 22.5 2 100 40
3 4 1 100 25
3 7 1 100 25
3 10 1 100 25
3 11 0 100 25
3 13 1 100 25
3 17 2 100 25
3 16 1 100 25
3 19 1 100 25
私は自分のEVIDのインデックスを作成するところまで行きます
rle(as.character(EVID))$lengths
A$Index<-unlist(sapply(rle(as.character(EVID))$lengths, seq_len), use.names = FALSE)
この状況では、このコードはave(EVID、EVID、FUN = seq_along)よりもうまく機能します。ave(EVID、EVID、FUN = seq_along)は、連続しているかどうかに関係なく、すべての1とすべての0にインデックスを付けます。Index=1とIndex=2の行の間に新しい行を挿入したい(最初の新しい行を手動で削除するだけです)。
ID TIME EVID AMT DOSE Index
1 1 10 1 100 20 1
2 1 12 1 100 20 2
3 1 14 1 100 20 3
4 1 16 1 100 20 4
5 1 17 0 100 20 1
6 1 18 1 100 20 1
7 1 20 1 100 20 2
8 1 22 1 100 20 3
9 2 5 1 100 40 4
10 2 10 1 100 40 5
11 2 15 1 100 40 6
12 2 17 0 100 40 1
13 2 20 1 100 40 1
14 3 4 1 100 25 2
15 3 7 1 100 25 3
16 3 10 1 100 25 4
17 3 11 0 100 25 1
18 3 13 1 100 25 1
19 3 16 1 100 25 2
20 3 19 1 100 25 3
結果のAには新しいインデックス列があります。新しい行をインデックス1と2の間に、つまりこの例では行番号1、6、13、19の後に配置します。
列ベクトルを作成し、定義された行番号で列を行としてデータに挿入できるソリューションに出くわしました。列エントリに基づいて行を追加し、いくつかのエントリを動的に決定するにはどうすればよいですか?
ご協力いただきありがとうございます!