Reputation: 33
How can I construct this matrix in R by for (loop)?
{[1000,100][1000,200][1000,300][2000,100][2000,200][2000,300][3000,100][3000,200][3000,300]};
Upvotes: 2
Views: 45
Reputation: 226087
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
Your use case really isn't clear to me, but I'll just point out that if you're doing this from scratch (i.e. you're going to be entering values manually), then here's the appropriate syntax (whitespace/newlines are optional, for clarity):
matrix(byrow=TRUE, ncol=2,
c(1000,100,
1000,200,
1000,300,
2000,100,
2000,200,
2000,300,
3000,100,
3000,200,
3000,300))
Upvotes: 4
Reputation: 160407
If you are starting from the string itself (and cannot generate it as Ben and Rui have discussed), then you can try parsing it:
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"
Then convert to numeric
with:
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
Upvotes: 3