anelson
anelson

Reputation: 55

Writing complex functions

I am new to creating functions in R... I have a formula I am trying to use to compute a new variable in my dataframe. I have tried writing a function to apply to mutate() but have been unsuccessful. The formula looks as follows:

x = 35(col2 - col1) + 35(col4 - col3)

I tried writing

val <- function(x) (35(y - x) + 35(v - w))

and entering in the column names in the mutate()...

df <- df %>% mutate(newcol= val(y=col2, x = col1, v = col4, w = col3)). 

I also tried directly putting the formula into mutate()

df <- df %>% mutate(newcol= 35(col2 - col1) + 35(col4 - col3)). 

I always get this error:

Error in df(df) : attempt to apply non-function

Can anyone provide guidance?

Upvotes: 0

Views: 318

Answers (2)

p0bs
p0bs

Reputation: 1034

I would just stick to the tidyverse to keep it simple.

First, create your object:

library(tidyverse)

df <- tibble(
  v = c(2, 4, 6),
  w = 0:2,
  x = 8:6,
  y = 9:7
)

... which generates:

# A tibble: 3 x 4
      v     w     x     y
  <dbl> <int> <int> <int>
1     2     0     8     9
2     4     1     7     8
3     6     2     6     7

And so calling ...

df %>% mutate(newcol= 35*(y-x) + 35*(v-w))

... yields ...

# A tibble: 3 x 5
      v     w     x     y newcol
  <dbl> <int> <int> <int>  <dbl>
1     2     0     8     9    105
2     4     1     7     8    140
3     6     2     6     7    175

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389355

Well, in R (35(y - x) + 35(v - w)) is not a valid syntax. You need to specify the multiplication operator explicitly.

You can directly do this in mutate :

library(dplyr)
df %>% mutate(x = 35 * (col2 - col1) + 35 * (col4 - col3))

Or if you want to create a function pass all the arguments as parameter of the function.

val <- function(x, y, v, w) 35 * (y - x) + 35 * (w - v)

and call it in mutate :

df %>% mutate(x = val(col1, col2, col3, col4))

Upvotes: 5

Related Questions