I'd like to build a function that takes a variable and then concatenates it with other letters within a function to refer to different variables in a frame. For example (code does not work):
set.seed(123)
frame <- data.frame(x = rnorm(100), p01u = rnorm(100), p01o = rnorm(100))
sum.fun <- function(frame, var){
xu <- cat(paste(var, "u", sep = ""))
xo <- cat(paste(var, "o", sep = ""))
print(sum(frame$xu))
print(sum(frame$xo))
}
sum.fun(frame, "p01")
The issue here is in the cat(paste()), but I can't quite figure out how to coerce it into a class that works. Any and all thoughts greatly appreciated.
You could remove the
catcalls and use[[to get the columns, as$does not work well with character arguments.To check:
Note: If you want multiple outputs from a function, I think it's best to use a
listfor the output. This way, you can have a vector of characters and a vector of numerics both classed as desired in the result. For example: