[R-sig-teaching] count the number of argument of a function

Kenn Konstabel lebatsnok at gmail.com
Tue Oct 20 22:37:46 CEST 2015


Hi Steve

length(formals()) will give you the number of formal arguments which is
always the same within a function. So this will not help if you plan to
have a variable number of args, as it seems. The following will work for
any number of arguments -- provided you feed it vectors of equal length! -
without the need of counting the length of args list

blah <- function(...) do.call(cbind, list(...))

Best regards

Kenn
On Oct 20, 2015 23:17, "Steven Stoline" <sstoline at gmail.com> wrote:

> Dear Michael:
>
> Thank you very much for your quick reply.
>
> Just one more thing. Assume we have these three data sets (vectors), but
> could be 4, 5  or more data sets.
>
> x1<-c(1,2,3,4,5)
> x2<-c(11,22,33,44,55)
> x3<-c(111,222,333,444,555)
>
>
> Inside the same fumction I do need to use the cbind() function to cbind
> these m (m could be 2, 3, 4, or any numbers) data sets. This what I trired,
> but it did not work.
>
> f <- function(x1,x2,x3){
>         m<-length(formals(sys.function()))
>
> print(m)
>
>     data<-cbind(x1,x2,...,xm)                                   #### I need
> some help with this part
>
> print(data)
>
> }
>
> f(x1,x2,x3)
>
>
>
> with thanks
> steve
>
>
>
> On Tue, Oct 20, 2015 at 3:51 PM, Michael Weylandt <
> michael.weylandt at gmail.com> wrote:
>
> > On Tue, Oct 20, 2015 at 2:45 PM, Steven Stoline <sstoline at gmail.com>
> > wrote:
> >
> >> Dear All:
> >>
> >> I am wondering whether there is a way to read and assign the number of
> >> arguments of a function inside this function.
> >>
> >>
> >> ### For example
> >>
> >> fun<-function(x1,x2,x3,...){
> >>
> >> m<- number of arguments
> >>
> >> }
> >>
> >> ### e.g.
> >>
> >> fun<-function(x1,x2,x3){
> >>
> >> m<- number of arguments
> >>
> >> ### m =3 in this case
> >>
> >> }
> >>
> >> ### e.g.
> >>
> >> fun<-function(x1,x2,x3,y1,z1,z2){
> >>
> >> m<- number of arguments
> >>
> >> ### m =6 in this case
> >>
> >> }
> >>
> >
> >
> > It's not entirely kosher, but
> >
> > length(formals(sys.function()))
> >
> > will work.
> >
> > f <- function(a, b,c, d, e, f){
> >     length(formals(sys.function()))
> > }
> >
> > f() ## 6
> >
>
>
>
> --
> Steven M. Stoline
> 1123 Forest Avenue
> Portland, ME 04112
> sstoline at gmail.com
>
>         [[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-teaching at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-teaching
>

	[[alternative HTML version deleted]]



More information about the R-sig-teaching mailing list