as a part of a bigger function, i need to create two new columns in a data.table (which is later on used to create a plot).
these are the names of my columns:
names(freqSevDataAge)
[1] "ag5" "claims" "exposure"
[7] "severity" "frequency"
I am trying to make this part of the function work:
testDT <- function(data, xvar, yvar, yvarsec, groupvar, ...){
freqSevDataAge2 <- freqSevDataAge[!claims == 0][, ':=' (scaled = "yvarsec" * max("yvar")/max("yvarsec"),
param = max("yvar")/max("yvarsec"))]
}
testDT(freqSevDataAge, xvar = "ag5", yvar = "severity", yvarsec = "frequency", groupvar = "gender")
the error i get is:
Error in "yvarsec" * max("yvar") : non-numeric argument to binary operator
EDIT:
The prposed solution using get()
worked, however now i am having troubles using the newly creates column in the ggplot . I get an error:
Error in f(...) : object 'param' not found
i checked the function step by stem and know that the column param
is created, the problem is calling it in the ggplot. How can i
getSecPlot <- function(data, xvar, yvar, yvarsec, groupvar, ...){
if ("agegroup" %in% xvar) xvar <- get("agegroup")
data <- data[!claims == 0][, ':=' (scaled = get(yvarsec) * max(get(yvar))/max(get(yvarsec)),
param = max(get(yvar))/max(get(yvarsec)))]
param <- unique(param)
sec_plot <- ggplot(data, aes_string (x = xvar, group = groupvar)) +
geom_col(aes_string(y = yvar, fill = groupvar, alpha = 0.5), position = "dodge") +
geom_line(aes(y = scaled, color = gender)) +
scale_y_continuous(sec.axis = sec_axis(~./(param),
name = paste0("average ", yvarsec), labels = function(x) format(x, big.mark = " ", scientific = FALSE))) +
labs(y = paste0("total ", yvar)) +
theme_pubclean()
}