Manually writing a function matrixpower() in R
It would be more efficient to use binary exponentiation.

Suppose that you want to raise an n by n matrix to the \$k^{th}\$ power.

The current method requires that you do a normal matrix multiplication \$k-1\$ times.

This of course has complexity \$k\$ multiplied by \$f(n)\$, Where \$f(n)\$ is the complexity of a matrix multiplication ( This is usually \$n^ 3\$ unless you write some fancy shmancy code that no one writes)

If you use binary exponentiation you reduce the number of multiplications to \$log(k)\$. Specifically the number of multiplications is the ceiling of \$log_2(k)\$ plus the number of 1 bits in the binary representation of \$k\$.

This is of course much more efficient for large values of \$k\$.