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.
We can use Map
in base R
df[] <- Map(`^`, df, powers)
Or map2
in purrr
purrr::map2_df(df, powers, `^`)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With