Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning output of a function to two variables in R [duplicate]

Tags:

r

Possible Duplicate:
function with multiple outputs

This seems like an easy question, but I can't figure it out and I haven't had luck in the R manuals I've looked at. I want to find dim(x), but I want to assign dim(x)[1] to a and dim(x)[2] to b in a single line.

I've tried [a b] <- dim(x) and c(a, b) <- dim(x), but neither has worked. Is there a one-line way to do this? It seems like a very basic thing that should be easy to handle.

like image 954
Eli Sander Avatar asked Jul 25 '12 13:07

Eli Sander


2 Answers

This may not be as simple of a solution as you had wanted, but this gets the job done. It's also a very handy tool in the future, should you need to assign multiple variables at once (and you don't know how many values you have).

Output <- SomeFunction(x)
VariablesList <- letters[1:length(Output)]
for (i in seq(1, length(Output), by = 1)) {
    assign(VariablesList[i], Output[i])
}

Loops aren't the most efficient things in R, but I've used this multiple times. I personally find it especially useful when gathering information from a folder with an unknown number of entries.

EDIT: And in this case, Output could be any length (as long as VariablesList is longer).

EDIT #2: Changed up the VariablesList vector to allow for more values, as Liz suggested.

like image 76
MikeZ Avatar answered Nov 15 '22 01:11

MikeZ


You can also write your own function that will always make a global a and b. But this isn't advisable:

mydim <- function(x) {
  out <- dim(x)
  a <<- out[1]
  b <<- out[2]
}

The "R" way to do this is to output the results as a list or vector just like the built in function does and access them as needed:

out <- dim(x)

out[1]

out[2]

R has excellent list and vector comprehension that many other languages lack and thus doesn't have this multiple assignment feature. Instead it has a rich set of functions to reach into complex data structures without looping constructs.

like image 39
Justin Avatar answered Nov 14 '22 23:11

Justin