[R] Question on creating list object

Stavros Macrakis macrakis at alum.mit.edu
Mon Nov 17 18:34:23 CET 2008

On Mon, Nov 17, 2008 at 5:00 AM, megh <megh700004 at yahoo.com> 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


More information about the R-help mailing list