My data looks like this:
ROW ID DV IDV
1 1 0 0.25
2 1 34 0.5
3 1 33 1
4 1 20 2
5 1 19 3
6 1 18 4
7 1 15 5
8 1 10 6
9 2 0 0.25
10 2 40 0.5
11 2 39 1
12 2 35 2
13 2 28 3
14 2 20 4
15 2 13 5
16 2 9 6
17 3 0 0.25
18 3 30 0.5
19 3 20 1
20 3 19 2
21 3 18 3
22 3 17 4
23 3 12 5
24 3 7 6
I want it to look like this :
ROW ID DV IDV NEWDV
1 1 0 0.25 0
2 1 34 0.5 34
3 1 33 1 33
4 1 20 2 20
5 1 19 3 9.5
6 1 18 4 4.5
7 1 15 5 1.875
8 1 10 6 0.375
9 2 0 0.25 0
10 2 40 0.5 40
11 2 39 1 39
12 2 35 2 35
13 2 28 3 28
14 2 20 4 20
15 2 13 5 6.5
16 2 9 6 2.25
17 3 0 0.25 0
18 3 30 0.5 30
19 3 20 1 20
20 3 19 2 19
21 3 18 3 9
22 3 17 4 4.25
23 3 12 5 1.5
24 3 7 6 0.4375
I have many datasets like this and I am trying to accomplish the same for each dataset. So, what I want to do is to create a column NEWDV by dividing DV values by 2,4,8,16,24,128 and so on(that is 2 raised to 1,2,3,4,5,6,7 and so on). I want to do this only when IDV > 2 and DV<20. For example take rows 21 to 24, for these four rows the condition of DV< 20 and IDV > 2 has been met and the NEWDV column reads 18/2=9 ,17/4=4.25,12/8=1.5,7/16=0.4375. This computation has to be reset for each ID.
I tried using the following code with no success:
fc is the object having the data
x <- c(2,4,8,16)
for(i in 1:4){
for(j in 1:4){
for(g in 1:length(fc$DV<20 & fc$ID==i & fc$IDV>2)) {
fc$NEWDV[g] <-ifelse(fc$DV[fc$ID==i][g]<20 & fc$IDV[fc$ID==i][g]>2,fc$DV[fc$ID==i][g]/x[j],fc$DV[fc$ID==j][g])
}
}
}
What am I doing wrong? Help is greatly appreciated!! I would like to only use a for loop for this problem. Any other solutions are also welcome. I am just familiar with for loops.Thank you.