如何计算R中所有可能组合的比率和归一化比率? [英] How to calculate ratios and normalized ratios in all possible combinations in R?

查看:96
本文介绍了如何计算R中所有可能组合的比率和归一化比率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算R中所有可能组合的归一化比率和简单比率。这是示例数据集

I want to calculate normalised ratios and simple ratios in all possible combinations in R. This is the sample dataset

df = structure(list(var_1 = c(0.035, 0.047, 0.004, 0.011, 0.01, 0.01, 
0.024), var_2 = c(0.034, 0.047, 0.004, 0.012, 0.01, 0.011, 0.025
), var_3 = c(0.034, 0.047, 0.006, 0.013, 0.011, 0.013, 0.026), 
    var_4 = c(0.034, 0.046, 0.008, 0.016, 0.014, 0.015, 0.028
    ), var_5 = c(0.034, 0.046, 0.009, 0.017, 0.015, 0.016, 0.029
    )), class = "data.frame", row.names = c(NA, -7L))

在得到

I could able to calculate simple ratios in all possible combinations after taking help from this.

do.call("cbind", lapply(seq_along(df), function(y) apply(df, 2, function(x) df[[y]]/x)))

但是我无法计算归一化比率.e。(xj-xi)/(xj + xi)以及如何正确命名每个计算出的比率?

But I am unable to calculate normalised ratios i.e. (xj - xi)/(xj + xi) and how to name each calculated ratios properly?

推荐答案

也许您可以尝试嵌套 lapply 来获取所有组合:

Perhaps, you can try nested lapply to get all the combinations :

cols <- 1:ncol(df)
mat <- do.call(cbind, lapply(cols, function(xj) 
          sapply(cols, function(xi) (df[, xj] - df[, xi])/(df[, xj] + df[, xi]))))

要分配列名,我们可以使用外部

To assign column names, we can use outer

colnames(mat) <-  outer(names(df), names(df), paste0)




我想我们可以直接使用列索引。


Thinking about it I think we can directly manipulate this using column indexes.

cols <- 1:ncol(df)
temp <- expand.grid(cols, cols)
new_data <- (df[,temp[,2]] - df[,temp[,1]])/(df[,temp[,2]] + df[,temp[,1]])

这篇关于如何计算R中所有可能组合的比率和归一化比率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆