0

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.

1
  • The cat function always returns NULL. Its only effect is a side effect at the console or to a file. Please read the help page. Also read ?'$', since that will not succeed with a character argument. Commented Nov 14, 2014 at 17:48

1 Answer 1

2

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" 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.