如何在R中为有序对制作矩阵?

问题描述 投票:1回答:2

我想在R中制作有序对的矩阵,即矩阵中的每个单元都包含点(a,b)。我试过这段代码:

calc_z<-function(results1){
#INPUT: Paired scores table
#OUTPUT: z score of a hypergeometric distribution as indicated in figure 1
a <- nrow(results1)
b <- ncol(results1)
results2 <- matrix(nrow = a ,ncol = b)
for (j in 1:b) {
 for (i in seq(1, a-3, 2)){
  results2[i, j] <- c(results1[i, j], results1[i+1, j])
  results2[i+1, j] <- c(results1[i+1, j], results1[i+2, j])
 }
results2[a-1, j] <- c(results1[a-1, j], results1[a, j])
results2[a, j] <- c(results1[a, j], results1[1, j])
}
`
`in my work: a=10, b=99`

该函数接受两个附近的变量并将它们绑定到一个点(a,b)(最后一行是最后一个数字)。当我尝试运行代码时,我收到一条消息:

Error in results2[i, j] <- c(results1[i, j], results1[i + 1, j]) : number of 
items to replace is not a multiple of replacement length

有什么问题以及如何解决?

另外:This is the data, I want to take every nearby games (1st and 2nd for example) and make them an ordered pair. I thought about summing but there is a difference between (0,1) and (1,0), so I need to leave it as an ordered pair.

这是数据,我想拍摄附近的每一场比赛(例如第一和第二场比赛)并使它们成为有序对。我想到了求和,但是(0,1)和(1,0)之间存在差异,所以我需要将其保留为有序对。

r matrix cartesian-product
2个回答
0
投票

如果你想在每个单元格中放入两个数字,你可以做以下其中一个我们为矩阵的1,1元素说明它:

# test input
x <- y <- 3

# character
mat1 <- matrix(nrow = 4, ncol = 7)
mat1[1, 1] <- paste(x, y)

# complex
mat2 <- matrix(nrow = 4, ncol = 7)
mat2[1, 1] <- x + 1i * y

# list
mat3 <- matrix(list(), nrow = 4, ncol = 7)
mat3[[1, 1]] <- c(x, y)

# numeric - encode assuming we know that largest element is < 1000
# and all elements are nonnegative
mat4 <- matrix(nrow = 4, ncol = 7)
mat4[1, 1] <- 1000 * x + y

0
投票

你是按专栏去的,对吧?确保安装dplyr软件包并尝试以下操作:

output <- apply(results1, 2L, function(column) {
  lead1 <- dplyr::lead(column, 1L, default=NULL)
  pairs <- paste0("(", column[-length(column)], ",", lead1, ")")
  # return
  pairs
})
© www.soinside.com 2019 - 2024. All rights reserved.