Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate ratios for every 2 columns in a data frame

Tags:

r

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.

like image 479
j lock Avatar asked Jan 13 '23 03:01

j lock


1 Answers

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)]

like image 60
Jilber Urbina Avatar answered Jan 18 '23 23:01

Jilber Urbina