Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutate across with vectorized function parameters

Tags:

dataframe

r

dplyr

I know the "across" paradigm is "many columns, one function" so this might not be possible. The idea is that I want to apply the same function to several columns with a parameter varying based on the column.

I got this to work using cur_column() but it basically amounts to computing the parameters 1 by 1 rather than providing a vector of equal size to the number of columns containing the parameters.

This first block produces what I want but it I'm wondering if there's a cleaner way.

library(dplyr)

df = data.frame(column1 = 1:100, column2 = 1:100)

parameters = data.frame(
    column_names = c('column1','column2'),
    parameters = c(10,100))
    
custom_function = function(x,addend){
    x + addend
}

df2 = df %>% mutate(
    across(x$column_names,
           ~custom_function(.,addend = x %>%
                                        filter(column_names == cur_column()) %>% 
                                        pull(parameters))))

What I would like to do for the last line would look like

df2 = df %>% mutate(
    across(x$column_names,~custom_function(.,addend = x$parameters)))
like image 903
tyler.reed Avatar asked Nov 19 '25 17:11

tyler.reed


1 Answers

We can do this in base with mapply:

mapply(`+`, df[,parameters$column_names], parameters$parameters)

##>      column1 column2
##> [1,]      11     101
##> [2,]      12     102
##> [3,]      13     103
##> [4,]      14     104
##> [5,]      15     105
##> ...
like image 72
M-- Avatar answered Nov 21 '25 06:11

M--