基本R程序设计

基本R程序设计,r,R,有没有比我更简单的编码方法 value = c(0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,1,0,0) first = matrix(value, nrow=6) second = matrix(rev(first),nrow=6) #reverse vector "value" output10 = cbind(first,second) output10 我只是很好奇是否有一种更简单的方法来编写代码,因为我发现我的代码“太初级了”。谢谢。您可以直接从值和版本(值)

有没有比我更简单的编码方法

value = c(0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,1,0,0)
first = matrix(value, nrow=6)
second = matrix(rev(first),nrow=6) #reverse vector "value"
output10 = cbind(first,second)
output10    

我只是很好奇是否有一种更简单的方法来编写代码,因为我发现我的代码“太初级了”。谢谢。

您可以直接从
版本(值)
的串联中创建结果矩阵:


value您可以创建一个0的矩阵,并使用索引将1放入所需的位置

mm <- matrix(0, 6, 6)
mm[col(mm) == row(mm) + 1 | col(mm) == row(mm) - 1] <- 1
mm

#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    0    1    0    0    0    0
# [2,]    1    0    1    0    0    0
# [3,]    0    1    0    1    0    0
# [4,]    0    0    1    0    1    0
# [5,]    0    0    0    1    0    1
# [6,]    0    0    0    0    1    0

mm假设您的目标是在非对角元素上分配
1
,则最适合大规模矩阵的方法是:

N = 100L
M = matrix(0L, N, N)

idx = seq_len(N - 1L)
M[cbind(c(idx, idx+1L), c(idx+1L, idx))] = 1L
M[1:6, 1:6]
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    0    1    0    0    0    0
# [2,]    1    0    1    0    0    0
# [3,]    0    1    0    1    0    0
# [4,]    0    0    1    0    1    0
# [5,]    0    0    0    1    0    1
# [6,]    0    0    0    0    1    0
这是通过使用模式创建元组来实现的,其中
1
s将是元组,并且只分配这些元组

稀疏
矩阵世界中,情况类似:

library(Matrix)
N = 1e8 # 100,000,000
idx = seq_len(N - 1L)

M = sparseMatrix(c(idx, idx + 1L), c(idx + 1L, idx))
M[1:6, 1:6]
6 x 6 sparse Matrix of class "ngCMatrix"

# [1,] . | . . . .
# [2,] | . | . . .
# [3,] . | . | . .
# [4,] . . | . | .
# [5,] . . . | . |
# [6,] . . . . | .

作为密集矩阵,这将是
1e16
整数元素,或80 PB,因此
M
(约1GB)在内存中保存并在几秒钟内声明是非常令人印象深刻的。这里的其他两种方法都会失败--
、和
修订
都会产生密集向量。

这比尝试将中心对角线设为1的泛化要好得多。
library(Matrix)
N = 1e8 # 100,000,000
idx = seq_len(N - 1L)

M = sparseMatrix(c(idx, idx + 1L), c(idx + 1L, idx))
M[1:6, 1:6]
6 x 6 sparse Matrix of class "ngCMatrix"

# [1,] . | . . . .
# [2,] | . | . . .
# [3,] . | . | . .
# [4,] . . | . | .
# [5,] . . . | . |
# [6,] . . . . | .