[英]Calculating division of unique pairs for each row in a matrix
在这里,我有一个5 * 4的矩阵(原来更大)。 我想计算矩阵每一行中每个唯一对的比率。
X1 X2 X3 X4
10 8 2 1
4 4 3 6
2 10 8 1
1 2 1 10
3 5 5 4
我想通过不重复的除法实现5 * 6矩阵,如下所示>
x1/x2 x1/x3 x1/x4 x2/x3 x2x4 x3/x4
1.25 5.00 10.00 4.00 8.00 2.00
1.00 1.33 0.67 1.33 0.67 0.50
0.20 0.25 2.00 1.25 10.00 8.00
0.50 1.00 0.10 2.00 0.20 0.10
0.60 0.60 0.75 1.00 1.25 1.25
目前,我已经创建了一个函数,希望可以解决这个问题,但是结果并不理想。
set.seed(7)
test <- data.frame(replicate(4,sample(1:10,5,rep=TRUE)))
func_calcRatio <- function(theMatrix){
ratios <- outer(theMatrix, theMatrix, '/')
ratios <- ratios[upper.tri(ratios)]
return(ratios)
}
func_ratioMatrix <- function(theMatrix){
ratios_list <- list()
i = 1
l = length(theMatrix)
for (i in 1:l) {
vec <- numeric(l)
for (j in 1:l){
vec[j] <- i^j
}
myrow <- theMatrix[,1]
onerow <- func_calcRatio(myrow)
ratios_list[[i]] <- onerow
i = i+1
}
ratios_df <- do.call("rbind", ratios_list)
return(ratios_df)
}
test.ratios <- func_ratioMatrix(test)
令上面的矩阵为A
那么您可以使用以下代码:
combn(4,2,function(x) A[,x[1]]/A[,x[2]])
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1.25 5.000000 10.0000000 4.000000 8.0000000 2.00
[2,] 1.00 1.333333 0.6666667 1.333333 0.6666667 0.50
[3,] 0.20 0.250000 2.0000000 1.250000 10.0000000 8.00
[4,] 0.50 1.000000 0.1000000 2.000000 0.2000000 0.10
[5,] 0.60 0.600000 0.7500000 1.000000 1.2500000 1.25
如果数据在数据框中而不是矩阵中,则可以使用数组操作:
例如。 让我们假设上面的矩阵是A=as.data.frame(A)
然后
combn(A,2,function(x)x[,1,]/x[,2,])
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1.25 5.000000 10.0000000 4.000000 8.0000000 2.00
[2,] 1.00 1.333333 0.6666667 1.333333 0.6666667 0.50
[3,] 0.20 0.250000 2.0000000 1.250000 10.0000000 8.00
[4,] 0.50 1.000000 0.1000000 2.000000 0.2000000 0.10
[5,] 0.60 0.600000 0.7500000 1.000000 1.2500000 1.25
您仍然可以按自己的方式修改代码。这只是一个粗略的想法。 希望能帮助到你
dat <- structure(list(X1 = c(10L, 4L, 2L, 1L, 3L), X2 = c(8L, 4L, 10L,
2L, 5L), X3 = c(2L, 3L, 8L, 1L, 5L), X4 = c(1L, 6L, 1L, 10L,
4L)), .Names = c("X1", "X2", "X3", "X4"), class = "data.frame", row.names = c(NA,
-5L))
当您逐行使用Apply时,您需要转置结果以按行获取值:
t( # this is the last function to execute, we will need to convert to row basis
apply(dat, 1, # loop over rows, single row at a time
function( r){ apply( combn(r,2), 2, # now loop over columns of `combn` result
function(x) x[[1]]/x[[2]]) }))
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1.25 5.000000 10.0000000 4.000000 8.0000000 2.00
[2,] 1.00 1.333333 0.6666667 1.333333 0.6666667 0.50
[3,] 0.20 0.250000 2.0000000 1.250000 10.0000000 8.00
[4,] 0.50 1.000000 0.1000000 2.000000 0.2000000 0.10
[5,] 0.60 0.600000 0.7500000 1.000000 1.2500000 1.25
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.