How to make object created within function usable outside

前端 未结 4 678
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-12 23:29

I created a function which produces a matrix as a result, but I can\'t figure out how to make the output of this function usable outside of the function environment, so that

4条回答
  •  醉梦人生
    2020-12-13 00:27

    At the end of the function, you can return the result.

    First define the function:

    getRangeOf <- function (v) {
        numRange <- max(v) - min(v)
        return(numRange)
    }
    

    Then call it and assign the output to a variable:

    scores <- c(60, 65, 70, 92, 99)
    scoreRange <- getRangeOf(scores)
    

    From here on use scoreRange in the environment. Any variables or nested functions within your defined function is not accessible to the outside, unless of course, you use <<- to assign a global variable. So in this example, you can't see what numRange is from the outside unless you make it global.

    Usually, try to avoid global variables at an early stage. Variables are "encapsulated" so we know which one is used within the current context ("environment"). Global variables are harder to tame.

提交回复
热议问题