如何在R中为有序对建立矩阵?

时间:2018-05-17 22:05:03

标签: r matrix cartesian-product

我想在 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)之间存在差异,所以我需要将它保留为有序对。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

你要走专栏,对吧?确保安装dplyr软件包并试试这个:

output <- apply(results1, 2L, function(column) {
  lead1 <- dplyr::lead(column, 1L, default=NULL)
  pairs <- paste0("(", column[-length(column)], ",", lead1, ")")
  # return
  pairs
})