Bo Liu
Bo Liu

Reputation: 41

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

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.

Upvotes: 4

Views: 922

Answers (3)

akrun
akrun

Reputation: 887971

In base R, we can replicate the 'powers' to make the lengths same and then apply the function

df ^ powers[col(df)]
#   v1 v2  v3
#1  1  4  27
#2  2  9  64
#3  3 16 125

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 40171

You can also try sweep()from base R:

sweep(df, 2, powers, "^")

  v1 v2  v3
1  1  4  27
2  2  9  64
3  3 16 125

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 389325

We can use Map in base R

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

Or map2 in purrr

purrr::map2_df(df, powers, `^`)

Upvotes: 4

Related Questions