[R] A Calculation on list object

Gabor Grothendieck ggrothendieck at gmail.com
Tue Jun 7 01:02:37 CEST 2011


On Mon, Jun 6, 2011 at 6:10 PM, Ron Michael <ron_michael70 at yahoo.com> wrote:
> Hello, I am into some calculation on a list object, therefore requesting the peers if there is any short cut way to so the same calculation.
>
> Let say I have following list object:
>
>> List <- vector('list', length = 3)
>> set.seed(1)
>> List[[1]] <- rnorm(5)
>> List[[2]] <- rnorm(2)
>> List[[3]] <- rnorm(7)
>> List
> [[1]]
> [1] -0.6264538  0.1836433 -0.8356286  1.5952808  0.3295078
>
> [[2]]
> [1] -0.8204684  0.4874291
>
> [[3]]
> [1]  0.7383247  0.5757814 -0.3053884  1.5117812  0.3898432 -0.6212406 -2.2146999
>
>>
>> Vector <- 3:5
>> Vector
> [1] 3 4 5
>
> Now, what I want to do is, add List with Vector, element-by-element. Means I wanted to do:
>
>> List[[1]] + Vector[1]
> [1] 2.373546 3.183643 2.164371 4.595281 3.329508
>> List[[2]] + Vector[2]
> [1] 3.179532 4.487429
>> List[[3]] + Vector[3]
> [1] 5.738325 5.575781 4.694612 6.511781 5.389843 4.378759 2.785300
>
> Till now I have done this calculation with for-loop. Therefore it would be interesting if there is any elegant way to do the same.
>

Try this:

mapply("+", List, Vector)



-- 
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