vtortola
vtortola

Reputation: 35963

list(...) vs as.list(...) when using the triple dot argument

I would like to get a list with the "..." parameters passed to the function.

myfunction <- function(..., a=1){
  parameters <- as.list(...)
  for(i in parameters){
    print(i)
  }
}

But when calling myfunction("x","y","z") I get a vector with one item:

## [1] "x"

Howerver, if I replace as.list(...) by simply list(...)

myfunction <- function(..., a=1){
  parameters <- list(...)
  for(i in parameters){
    print(i)
  }
}

it works:

## [1] "x"
## [1] "y"
## [1] "z"

So why is as.list(...) behaving differently?

Cheers.

Upvotes: 4

Views: 1990

Answers (1)

Pierre L
Pierre L

Reputation: 28461

You may be looking for the c concatenate function.

as.list(c('x', 'y', 'z'))
#[[1]]
#[1] "x"
#
#[[2]]
#[1] "y"
#
#[[3]]
#[1] "z"

myfunction <- function(..., a=1){
  parameters <- as.list(c(...))
  for(i in parameters){
    print(i)
  }
}

myfunction('x', 'y', 'z')
#[1] "x"
#[1] "y"
#[1] "z"

I don't want to get the explanation wrong, so I'll let someone else explain why.

Upvotes: 3

Related Questions