[R] Assigning a vector to every element of a list.

Gabor Grothendieck ggrothendieck at gmail.com
Tue Jul 3 08:02:37 CEST 2012

On Mon, Jul 2, 2012 at 6:16 PM, Spencer Maynes <smaynes89 at gmail.com> wrote:
> I have a vector d of unknown length, and a list b of unknown length. I
> would like to replace every element of b with d. Simply writing b<-d does
> not work as R tries to fit every element of d to a different element of d,
> and b<-rep(d,length(b)) does not work either as it makes a list of
> length length(d)*length(b) not a list of length(b). I know how to do this
> with a for loop, but I feel that there has to be a more efficient way. Any
> suggestions?

Try this where the first line creates a list, L, whose elements we
want to replace and the second line replaces every element with the
indicated vector:

> L <- list(1, 1:2, "abc")
> L[] <- list(1:4)
> L
[1] 1 2 3 4

[1] 1 2 3 4

[1] 1 2 3 4

Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

More information about the R-help mailing list