Assigning function output to two variables in R

Possible duplicate:
with multiple outputs

This seems like a simple question, but I can't figure it out, and I was out of luck in the R manuals I looked at. I want to find dim(x) , but I want to assign dim(x)[1] to a and dim(x)[2] to b on the same line.

I tried [ab] <- dim(x) and c(a, b) <- dim(x) , but none of them worked. Is there one way to do this? This seems like a very simple thing that needs to be easily handled.

+4
source share
4 answers

It may not be as simple as we would like, but it does its job. It is also a very convenient tool in the future if you need to assign several variables at once (and you do not 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 are not the most efficient in R, but I have used this several times. For me personally, this is especially useful when collecting information from a folder with an unknown number of records.

EDIT: And in this case, Output can be any length (as long as the VariablesList is larger).

EDIT # 2: changed the VariablesList vector so that there are more values, as Liz suggested.

0
source

You can also write your own function that will always do global a and b . But this is not recommended:

 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 in the same way as the built-in function, and access them as necessary:

 out <- dim(x) out[1] out[2] 

R has an excellent list and understanding of the vector, which many other languages ​​lack and therefore do not have this multiple assignment function. Instead, it has a rich set of functions for accessing complex data structures without creating loops.

+1
source

There doesn't seem to be a way to do this. In fact, the only way to handle this is to add a couple of extra lines:

 temp <- dim(x) a <- temp[1] b <- temp[2] 
0
source

It depends on what is in a and b . If they are just numbers, try returning the vector as follows:

 dim <- function(x,y) return(c(x,y)) dim(1,2)[1] # [1] 1 dim(1,2)[2] # [1] 2 

If a and b are something else, you might want to return a list

 dim <- function(x,y) return(list(item1=x:y,item2=(2*x):(2*y))) dim(1,2)[[1]] [1] 1 2 dim(1,2)[[2]] [1] 2 3 4 

EDIT:

try the following: x <- c(1,2); names(x) <- c("a","b") x <- c(1,2); names(x) <- c("a","b")

-1
source

All Articles