We can do this with outer.
b <- 1:4; p <- 1:3
outer(b, p, `^`)
# [,1] [,2] [,3]
# [1,] 1 1 1
# [2,] 2 4 8
# [3,] 3 9 27
# [4,] 4 16 64
If a vector is needed, as.vector
outer(b, p, `^`) |> as.vector()
And a list
outer(b, p, `^`) |> as.data.frame() |> as.list()
# $V1
# [1] 1 2 3 4
#
# $V2
# [1] 1 4 9 16
#
# $V3
# [1] 1 8 27 64
A loop could look like this,
b <- 1:4; p <- 1:3
res <- array(dim=c(length(b), length(p)))
for (i in seq_along(b)) {
for (j in seq_along(p)) {
res[i, j] <- b[i]^p[j]
}
}
res
# [,1] [,2] [,3]
# [1,] 1 1 1
# [2,] 2 4 8
# [3,] 3 9 27
# [4,] 4 16 64
but it is very inefficient in R.
We could do it in Rcpp, though.
Rcpp::sourceCpp(code='
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix powv(NumericVector b, NumericVector p) {
int blen = b.size();
int plen = p.size();
NumericMatrix m(blen, plen);
for (int i = 0; i < blen; i++) {
for (int j = 0; j < plen; j++) {
m(i, j) = std::pow(b[i], p[j]);
}
}
return m;
}
')
powv(b, p)
# [,1] [,2] [,3]
# [1,] 1 1 1
# [2,] 2 4 8
# [3,] 3 9 27
# [4,] 4 16 64
Microbenchmark
b <- seq(0, 5, .01); p <- seq(0, 5, .01)
microbenchmark::microbenchmark(
outer=outer(b, p, `^`),
powv=powv(b, p),
Power_rui=Power(b, p),
`for`=forfun(b, p),
check='equal'
)
# Unit: milliseconds
# expr min lq mean median uq max neval
# outer 9.700440 9.922495 10.341630 9.981673 10.081983 13.71488 100
# powv 6.389418 6.418062 6.552114 6.434775 6.478917 8.35611 100
# Power_rui 11.074284 11.131459 11.433523 11.178858 11.267215 13.77799 100
# for 39.902641 40.970678 42.190528 42.313148 42.825829 47.53356 100