-2

adding as integers instead of list elements in R

I am getting

> total = 0
> for (qty in a[5]){
+ total = total + as.numeric(unlist(qty))
+ print(total)
+ }
 [1] 400 400 400 400 400 400 400 400 400 400

what i really want is :

> total = 0
> for (qty in a[5]){
+ total = total + as.numeric(unlist(qty))
+ print(total)
+ }
 [1] 400 800 1200 1600 2000 2400 2800 3200 3600 4000

refine: a little bit more to a more specific scenario,

price buy_sell  qty
100        B  100
100        B  200
90        S  300
100        S  400

I want to make a forth column

price buy_sell  qty net
100        B  100   10000
100        B  200   30000
90        S  300    3000
100        S  400   -37000
danielho
  • 17
  • 3

1 Answers1

2

Note that if a is a list, you want to use double brackets. Otherwise you are getting back a list of size one, where the first element has the values you are looking for

Try:

 total <- cumsum(a[[5]])


a <- list()
a[[5]] <- rep(400, 10)

cumsum(a[[5]])
#  [1]  400  800 1200 1600 2000 2400 2800 3200 3600 4000

Compare:

 a[5]
 a[[5]]
 a[5][[1]]
Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178