r - 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!
解决方案
它本质上是对 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
推荐阅读
- binary - 以 1 开头的 8 位数字的紧凑公式
- javascript - 将参数传递给 Vue 路由器元标题
- c - 指针的 scanf 函数不起作用(对于使用指针指针的矩阵)
- go - 将 RFC3339 字符串解析为时间时无法将时间解析为 T
- java - 如果记录没有字段,Mongo-Spark 连接器会在读取时跳过对象
- kotlin - Kotlin 四字节 unicode 文字?
- docker-compose - docker swarm restart 'any' 的意思
- java - WebFlux 主体序列化为依赖于运行时的模型?
- c++ - 各种 c++ 编译器的模棱两可的行为
- php - 两次调用模板选择(Select2 Kartik-yii2)