I want to write a function that creates new variables in a dataframe based on strings read from a SQL table. The function should take two arguments, df and str, and return df with an extra column appended. str will be string of the form "a = f(B)", where a is a column of df, B is a set of columns of df, and f is the transformation function.
Example:
df <- data.frame(EventID = c(111,112,113), Day = c(6,8,15))
What I want is transform(df, Week = ceiling(Day / 7)), but I can’t figure out how to pass the string "Week = ceiling(Day / 7)" (as a variable of type character) to the ... arguments of transform.
I’ve tried various combinations of parse and eval, but I can’t figure out how to change a character object into what the R documentation describes as a “tagged vector expression.”
Here is one way: