首页 > 解决方案 > Calculate Ratio of multiple pairs of columns

问题描述

I have a table in R like this one:

id  v1  v2  v3
1   115 116 150
2   47  50  55
3   70  77  77

I would like to calculate the ratio between v2/v1 as (v2/v1)-1, v3/v2 as (v3/v2)-1 and so on (I have around 55 variables, and need to get values like this:

id  v1  v2  v3  rat1    rat2
1   115 116 150 0.01    0.29
2   47  50  55  0.06    0.10
3   70  77  77  0.10    0.00

Is there a workaround so I don´t have to code each pair independently?

Thx!

标签: r

解决方案


它本质上是对 columni和 column的循环i+1,您可以编写一个for循环来执行此操作。或者在 R 语言中,使用矢量化函数,例如Map/ mapply

vars <- paste0("v",1:3)
outs <- paste0("rat",1:2)
dat[outs] <- mapply(`/`, dat[vars[-1]], dat[vars[-length(vars)]]) - 1

dat
#  id  v1  v2  v3        rat1      rat2
#1  1 115 116 150 0.008695652 0.2931034
#2  2  47  50  55 0.063829787 0.1000000
#3  3  70  77  77 0.100000000 0.0000000

推荐阅读