Apply function across selected columns returning one column

I have some existing code that looks like this

library(dplyr)
iris %>% mutate(output = purrr::invoke(pmin, across(starts_with("Sepal"))))

There are many columns that need to be included, so it would be better to not have to write them out.

There are two problems with this code

  1. invoke is deprecated, and
  2. It looks unnecessarily (maybe?) complicated

The change suggested by the help file returns an error ie just placing "!!!" in front of across.

# Before:
invoke(mean, list(na.rm = TRUE), x = 1:10)

# After
exec(mean, 1:10, !!!list(na.rm = TRUE))

Anyway, I can't remember why I wrote the code the way that I did, it seems unnecessarily complex. Am I missing some obvious way to compute a function mapping a subset of columns to one column?

Thanks!

Part of the difficulty is that pmin needs a list of arguments.

Here is an inelegant solution.

iris %>% mutate(output = sapply(across(starts_with("Sepal")), pmin))

I feel like I'm misusing across to give starts_with the right context.

you may have a usecase around the results going into output that I dont know, but generally I think a good way is

iris %>% mutate(across(starts_with("Sepal"), list(pmin=pmin)))

which labels the new columns by their column name followed by the function used, but the benefit you have is that you have conventional columns in your results frame, rather than a column being a matrix etc.

This produces two columns, I was looking for output as one column with the minimum computed rowwise over all the selected columns.

Using a simplified version of this answer: r - Get the rowwise minimum of certain columns excluding 0 and NA - Stack Overflow

iris %>% rowwise() %>% mutate(output = min(c_across(starts_with("Sepal"))))
target <- grep("^Sepal",colnames(iris))
apply(iris[target],1,min) |> as.numeric()
#>   [1] 3.5 3.0 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 3.7 3.4 3.0 3.0 4.0 4.4 3.9 3.5
#>  [19] 3.8 3.8 3.4 3.7 3.6 3.3 3.4 3.0 3.4 3.5 3.4 3.2 3.1 3.4 4.1 4.2 3.1 3.2
#>  [37] 3.5 3.6 3.0 3.4 3.5 2.3 3.2 3.5 3.8 3.0 3.8 3.2 3.7 3.3 3.2 3.2 3.1 2.3
#>  [55] 2.8 2.8 3.3 2.4 2.9 2.7 2.0 3.0 2.2 2.9 2.9 3.1 3.0 2.7 2.2 2.5 3.2 2.8
#>  [73] 2.5 2.8 2.9 3.0 2.8 3.0 2.9 2.6 2.4 2.4 2.7 2.7 3.0 3.4 3.1 2.3 3.0 2.5
#>  [91] 2.6 3.0 2.6 2.3 2.7 3.0 2.9 2.9 2.5 2.8 3.3 2.7 3.0 2.9 3.0 3.0 2.5 2.9
#> [109] 2.5 3.6 3.2 2.7 3.0 2.5 2.8 3.2 3.0 3.8 2.6 2.2 3.2 2.8 2.8 2.7 3.3 3.2
#> [127] 2.8 3.0 2.8 3.0 2.8 3.8 2.8 2.8 2.6 3.0 3.4 3.1 3.0 3.1 3.1 3.1 2.7 3.2
#> [145] 3.3 3.0 2.5 3.0 3.4 3.0

Created on 2023-10-12 with reprex v2.0.2

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.