[R] Can elements of a list be passed as multiple arguments?

David Winsemius dwinsemius at comcast.net
Wed Dec 9 19:59:34 CET 2009


On Dec 9, 2009, at 12:14 PM, Peng Yu wrote:

> On Tue, Dec 8, 2009 at 11:05 PM, David Winsemius <dwinsemius at comcast.net 
> > wrote:
>>
>> On Dec 8, 2009, at 11:37 PM, Peng Yu wrote:
>>
>>> I want to split a matrix, where both 'u' and 'w' are results of
>>> possible ways. However, whenever 'n' changes, the argument passed to
>>> mapply() has to change. Is there a way to pass elements of a list as
>>> multiple arguments?
>>
>> You need to explain what you want in more detail. In your example  
>> mapply did
>> exactly what you told it to. No errors. Three matrices. What were you
>> expecting when you gave it three lists in each argument?
>
> I want a general solution so that I don't have to always write
> "v[[1]], v[[2]], ..., v[[n]]" like in the following, because the
> following way would not work if 'n' is an arbitrary number.
>
> w=mapply(function(x,y) {cbind(x,y)}, v[[1]], v[[2]], ..., v[[n]])
>
> One way that I can think of is to somehow expand a list (i.e., v in
> this case) to a set of arguments that can be passed to 'mapply()'.

The functions illustrated on the help page for Reduce address the task  
of passing arbitrarily long lists of arguments to functions expecting  
two. It's possible that do.call might address this, but I have not  
come up with a strategy that deals with your structures.

-- 
David.


>
>>> m=10
>>> n=2
>>> k=3
>>>
>>> set.seed(0)
>>> x=replicate(n,rnorm(m))
>>> f=sample(1:k, size=m, replace=T)
>>>
>>> u=split(as.data.frame(x),f)
>>>
>>> v=lapply(
>>>   1:dim(x)[[2]]
>>>   , function(i) {
>>>     split(x[,i],f)
>>>   }
>>>   )
>>>
>>> w=mapply(
>>>   function(x,y) {
>>>     cbind(x,y)
>>>   }
>>>   , v[[1]], v[[2]]
>>>   )
>>
>> --
>>
>> David Winsemius, MD
>> Heritage Laboratories
>> West Hartford, CT
>>
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list