Re: [R] Question on creating list object

From: Stavros Macrakis <>
Date: Mon, 17 Nov 2008 12:34:23 -0500

On Mon, Nov 17, 2008 at 5:00 AM, megh <> wrote:
>> lapply(1:5, function(i) c(1,2,3)^i)
> [[1]]
> [1] 1 2 3
> This is fine. However my goal is : each element of this list should depend
> on previous element like :
> lis # List name
> then,
> lis[[i]] = lis[[i-1]] + c(1,2,3)^i
> How can I modify my current code without having a "for" loop ?

This is a cumulative sum, so you can use Reduce with the accumulate parameter:

     Reduce(`+`, lapply(1:5,`^`,c(1,2,3)),accumulate=TRUE)

You might think (actually, I thought this too until I tried it) that cumsum(X) == Reduce(`+`,X,accumulate=TRUE), but it is not: cumsum only handles vectors of numbers (what R calls "numeric objects"), not lists of other types (such as vectors of numbers), even if `+` is defined on them.

              -s mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Mon 17 Nov 2008 - 17:41:11 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 17 Nov 2008 - 18:30:29 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive