You can use a package called magic
:
library(magic)
magic(4)
output looks like this:
# [,1] [,2] [,3] [,4]
# [1,] 1 12 8 13
# [2,] 15 6 10 3
# [3,] 14 7 11 2
# [4,] 4 9 5 16
You cannot decide what is the sum for the matrix. It is going to be:
.
Where "n" is the dimension of the matrix.
But you can multiply it by a number (preferably an integer).
Useful Link: What is Magic Square?
How to look into a function?
If you want to figure out how magic
function works, you can use this and dig into it step-by-step;
>functionBody(magic)
# {
# if (length(n) > 1) {
# return(sapply(n, match.fun(sys.call()[[1]])))
# }
# n <- round(n)
# if (n == 2) {
# stop("Normal magic squares of order 2 do not exist")
# }
# if (n%%2 == 1) {
# return(as.standard(magic.2np1(floor(n/2))))
# }
# if (n%%4 == 0) {
# return(as.standard(magic.4n(round(n/4))))
# }
# if (n%%4 == 2) {
# return(as.standard(magic.4np2(round((n - 2)/4))))
# }
# stop("This cannot happen")
# }
You need to look into other functions that appears above to fully comprehend the process.