I have a dataframe with several variables listed by year. I want to divide a set of variables by other variables of the same year. So for example:
Dataframe:
Variable: A B C D AA BB CC DD
I want to create new columns of A/AA B/BB C/CC D/DD etc..
I have tried creating a function:
i<- 1:4
ii<-5:8
A<- function(x){i/ii}
Then running the apply function:
apply(dataframe[1:8], 2, A)
But this is not correct. Please help!
Is this what you're looking for?
a<-as.data.frame(matrix(80:1,ncol=8))
a
V1 V2 V3 V4 V5 V6 V7 V8
1 80 70 60 50 40 30 20 10
2 79 69 59 49 39 29 19 9
3 78 68 58 48 38 28 18 8
4 77 67 57 47 37 27 17 7
5 76 66 56 46 36 26 16 6
6 75 65 55 45 35 25 15 5
7 74 64 54 44 34 24 14 4
8 73 63 53 43 33 23 13 3
9 72 62 52 42 32 22 12 2
10 71 61 51 41 31 21 11 1
a[1:4]/a[5:8]
V1 V2 V3 V4
1 2.000000 2.333333 3.000000 5.000000
2 2.025641 2.379310 3.105263 5.444444
3 2.052632 2.428571 3.222222 6.000000
4 2.081081 2.481481 3.352941 6.714286
5 2.111111 2.538462 3.500000 7.666667
6 2.142857 2.600000 3.666667 9.000000
7 2.176471 2.666667 3.857143 11.000000
8 2.212121 2.739130 4.076923 14.333333
9 2.250000 2.818182 4.333333 21.000000
10 2.290323 2.904762 4.636364 41.000000