1

I would like to use a function in order to calculate a new variable based on existing variables within a dataframe. The name of the new variable should be defined as a function argument: e.g. function(df, varname = "myVarname"):

calculateTime <- function(df, varname){
 df <- df %>% mutate(varname = end - begin )
 return(df)
}

calculateTime(df, "myVarname")

Unfortunately, this code doesn't work.

Can anyone help me?

D. Studer
  • 1,711
  • 1
  • 16
  • 35

1 Answers1

0

I suggest you can change 'myVarName' string to df column hash inside calculateTime() function:

## some random data ##
df <- data.frame(end = seq(1:10), begin = seq(1:10))

## applying calculateTime() function ##

calculateTime(df, df$varname)

Console Output:

#   end begin varname
#1    1     1       0
#2    2     2       0
#3    3     3       0
#4    4     4       0
#5    5     5       0
#6    6     6       0
#7    7     7       0
#8    8     8       0
#9    9     9       0
#0   10    10       0
AlSub
  • 1,384
  • 1
  • 14
  • 33