Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a vector of values as parameters for mutate?

Tags:

r

dplyr

I am writing a code which is expected to raise each column of a data frame to some exponent.

I've tried to use mutate_all to apply function(x,a) x^a to each column of the dataframe, but I am having trouble passing values of a from a pre-defined vector.

powers <- c(1,2,3)
df <- data.frame(v1 = c(1,2,3), v2 = c(2,3,4), v3 = c(3,4,5))
df %>% mutate_all(.funs, ...)

I am seeking help on how to write the parameters of mutate_all so that the elements of powers can be applied to the function for each column.

I expect the output to be a data frame, with columns being (1,2,3),(4,9,16),(27,64,125) respectively.

like image 528
Bo Liu Avatar asked Mar 03 '23 10:03

Bo Liu


1 Answers

We can use Map in base R

df[] <- Map(`^`, df, powers)

Or map2 in purrr

purrr::map2_df(df, powers, `^`)
like image 94
Ronak Shah Avatar answered Mar 28 '23 05:03

Ronak Shah