Can you assign two variables simultaneously in R?

后端 未结 2 1482
情话喂你
情话喂你 2021-01-25 00:06

I am using the example of calculating the length of the arc around a circle and the area under the arc around a circle based on the radius of the circle (r) and the angle of the

相关标签:
2条回答
  • 2021-01-25 00:38

    No, you can't do that in R (at least, not in base or any packages I'm aware of).

    The closest you could come would be to assign objects to different elements of a list. If you really wanted, you could then use list2env to put the list elements in an environment (e.g., the global environment), or use attach to make the list elements accessible, but I don't think you gain much from these approaches.

    If you want a function to return more than one value, just put them in a list. See also r - Function returning more than one value.

    You can assign multiple variables the same value as below. Even here, I think the code is unusual and less clear, I think this outweighs any benefits of brevity. (Though I suppose it makes it crystal clear that all of the variables are the same value... perhaps in the right context it makes sense.)

    x <- y <- z <- 1
    # the above is equivalent to
    x <- 1
    y <- 1
    z <- 1
    
    0 讨论(0)
  • 2021-01-25 00:41

    As Gregor said, there's no way to do it exactly as you said and his method is a good one, but you could also have a vector represent your two values like so:

    # Function that adds one value and returns a vector of all the arguments.
    plusOne <- function(vec) {
    
      vec <- vec + 1
      return(vec)
    
    }
    
    # Creating variables and applying the function.
    x <- 1
    y <- 2
    z <- 3
    vec <- c(x, y, z)
    vec <- plusOne(vec)
    

    So essentially you could make a vector and have your function return vectors, which is essentially filling 3 values at once. Again, not what you want exactly, just a suggestion.

    0 讨论(0)
提交回复
热议问题