简体   繁体   中英

Passing arguments to functions, and variable scopes in R

I'm writing a simple function that takes two arguments (state, outcome). State is used to subset a dataframe later.

Having said that, part of the requirement is that state be a length 2 character vector. I need to write more code to ensure that the state that is passed conforms to this requirement.

So I wrote the following:

best <- function(state, outcome) {

  outcome <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
  state <- vector(mode = "character", length = 2)
  st.checkTbl <- outcome[8]

  state
  }

However, when I call the function and pass the arguments:

best("AXA") or best("FOO") or even best("TX") or best(AL)

All I get back is: "" ""

If I comment out the #state <- ... then it passes the argument just fine and it prints "FOO" or "AXA" or "TX", etc.

How can I ensure that the argument passed to the function is stored as a variable (state) in the function? Or, am I way overthinking this? Really I just wanted to test that what I am passing to the state argument can be printed for test purposes.

. Sorry for the 101 lesson.

You would generally read your data outside of any function, like so:

outcome.data <- read.csv("outcome-of-care-measures.csv", colClasses = "character")

Otherwise, since a function has its own namespace , all the variables defined inside of it will vanish upon its return, unless they themselves are returned by the function with return(...) . Several objects can be returned by putting them in a list: return(list(item1=var1, item2=var2)) .

Some functions, such as assign , have the envir parameter that can be set to .GlobalEnv to change this behavior. Altering an object can also be done inside a function using the <<- operator instead of <- , although this practice is generally recommended against.

As a side note, when using a function, you need to define clearly:

  1. What are its inputs
  2. What does it do
  3. What does it return

It's not useful, for instance, to use outcome as a function parameter and then read into a variable named income the content of a csv file. Your argument is then useless as it will be written over. That's why you had to comment out the line defining your state variable inside the function to actually be able to use state as it was received by the function.

This surely won't answer all your questions, but hopefully it can help you clarify certain things. For the rest there are plenty of good tutorials to learn further on how to program in R and how/when to use functions. Best of luck and happy learning!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM