创建一个给定的矩阵

时间:2019-08-19 17:05:14

标签: r matrix

如何通过for(循环)在R中构造此矩阵?

{[1000,100][1000,200][1000,300][2000,100][2000,200][2000,300][3000,100][3000,200][3000,300]};

2 个答案:

答案 0 :(得分:4)

x <- expand.grid((1:3)*100,(1:3)*1000)  ## construct data frame of all combinations
as.matrix(x[2:1])                       ## reverse column order, convert to matrix

您的用例对我来说确实不是很清楚,但是我只是指出,如果您是从头开始执行此操作(即,您将要手动输入值),那么这里是适当的语法(空格) / newlines是可选的(为清楚起见):

matrix(byrow=TRUE, ncol=2,
       c(1000,100,
         1000,200,
         1000,300,
         2000,100,
         2000,200,
         2000,300,
         3000,100,
         3000,200,
         3000,300))

答案 1 :(得分:3)

如果您是从 string 本身开始的(并且无法像Ben和Rui讨论的那样生成),则可以尝试解析它:

txt <- '{[1000,100][1000,200][1000,300][2000,100][2000,200][2000,300][3000,100][3000,200][3000,300]};'
m <- do.call(rbind, strsplit(strsplit(txt, "[^,0-9]+")[[1]], ","))
m
#       [,1]   [,2] 
#  [1,] "1000" "100"
#  [2,] "1000" "200"
#  [3,] "1000" "300"
#  [4,] "2000" "100"
#  [5,] "2000" "200"
#  [6,] "2000" "300"
#  [7,] "3000" "100"
#  [8,] "3000" "200"
#  [9,] "3000" "300"

然后使用以下命令转换为numeric

m <- apply(m, 2, as.numeric)
m
#       [,1] [,2]
#  [1,] 1000  100
#  [2,] 1000  200
#  [3,] 1000  300
#  [4,] 2000  100
#  [5,] 2000  200
#  [6,] 2000  300
#  [7,] 3000  100
#  [8,] 3000  200
#  [9,] 3000  300