Reputation: 1295
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.
Upvotes: 0
Views: 33
Reputation: 99371
You could remove the cat
calls and use [[
to get the columns, as $
does not work well with character arguments.
sum.fun <- function(frame, var) {
xu <- paste0(var, "u")
xo <- paste0(var, "o")
setNames(c(sum(frame[[xu]]), sum(frame[[xo]])), c(xu, xo))
}
sum.fun(frame, "p01")
# p01u p01o
# -10.75468 12.04651
To check:
with(frame, c(sum(p01u), sum(p01o)))
# [1] -10.75468 12.04651
Note: If you want multiple outputs from a function, I think it's best to use a list
for 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:
sum.fun2 <- function(frame, var){
xu <- paste0(var, "u")
xo <- paste0(var, "o")
list(names = c(xu, xo), values = c(sum(frame[[xu]]), sum(frame[[xo]])))
}
(sf2 <- sum.fun2(frame, "p01"))
# $names
# [1] "p01u" "p01o"
#
# $values
# [1] -10.75468 12.04651
sapply(sf2, class)
# names values
# "character" "numeric"
Upvotes: 2