Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add map_*_matrix functions similar to vapply with FUN.VALUE of length > 1. #798

Closed
AshesITR opened this issue Oct 15, 2020 · 1 comment
Closed

Comments

@AshesITR
Copy link
Contributor

AshesITR commented Oct 15, 2020

Sometimes I need to compute a matrix column-wise using a function.
Base-R code to achieve that would be vapply() with a FUN.VALUE of length greater than 1.

For a toy example with an easier solution consider this function:

rnorm_mat <- function(n, means = 0:5, sd = 1) {
  vapply(
    means,
    function(mu) rnorm(n, mean = mu, sd = sd),
    numeric(n)
  )
}

If n > 1, this works as expected and returns a matrix of normal random variates with true column means means and constant standard deviation sd. However, the return type is not stable for n = 1 in which case the value will be a length length(means) vector instead of a 1-row matrix.

I propose a family of functions map_*_matrix() which always return a matrix and behaviour akin to

map_dbl_matrix <- function(.x, .f, .n, ...) {
  .f <- purrr::as_mapper(.f, ...)
  res <- vapply(.x, .f, numeric(.n), ...)
  dim(res) <- c(.n, length(.x))
  res
}

Maybe additional convenience arguments such as .byrow = FALSE to decide whether to create the matrix rowwise or column-wise are necessary as well.

If there is interest in such a feature, I'll gladly try to get a PR started, so please let me know.

@hadley
Copy link
Member

hadley commented Aug 24, 2022

I think this is out of scope for purrr, since we don't currently have functions that return matrices and I don't think we want to increase the API size so much.

@hadley hadley closed this as completed Aug 24, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants