I'm new to R, so this question maybe very simple to many of you. I have a data frame with 1000 columns, and 1000 rows, a bit like the follow
id S1 S2 S3 S4 S5 S6
A1 2 7 9 56 34 23
A2 3 5 11 4 8 56
A3 8 22 32 45 67 76
A4 4 21 23 1 34 43
A5 6 12 5 19 36 46
A6 45 89 76 87 75 78
A7 45 71 56 65 34 87
A8 26 76 67 87 65 65
I'd like to get the ratio of column 1/2, column 3/4, ...column 999/1000, and then put in a matrix. I tried using "for" to do it, but never succeeded. Anyone can help me on this? Thank you.
No need to use for, use seq to create an index for selecting the columns in the numerator and denominator
> num <- seq(2,ncol(df),2) # index for numerator
> dem <- seq(3,ncol(df),2) # index for denominator
> df[, num] / df[, dem]
S1 S3 S5
1 0.2857143 0.1607143 1.4782609
2 0.6000000 2.7500000 0.1428571
3 0.3636364 0.7111111 0.8815789
4 0.1904762 23.0000000 0.7906977
5 0.5000000 0.2631579 0.7826087
6 0.5056180 0.8735632 0.9615385
7 0.6338028 0.8615385 0.3908046
8 0.3421053 0.7701149 1.0000000
All in one shot: df[,seq(2,ncol(df),2)] / df[, seq(3,ncol(df),2)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With