Reputation: 373
I have a list called good, I want to calculate the difference between two values within each vector.
good[1:2]
[[1]]
[1] 8 16 28 38 53
[[2]]
[1] 1 7 9 16 40
so I will get another list
good_dif1[1:2]
[[1]]
[1] 8 12 10 15
[[2]]
[2] 6 2 7 24
if I want insert a NA to first value, how can I do that?
so I will get another list
good_dif2[1:2]
[[1]]
[1] NA 8 12 10 15
[[2]]
[2] NA 6 2 7 24
Upvotes: 3
Views: 3378
Reputation: 99331
> good <- list(c(8, 16, 28, 38, 53), c(1, 7, 9, 16, 40))
> good_dif1 <- lapply(good, diff)
> good_dif2 <- lapply(good_dif1, function(x) append(NA, x))
> good_dif2
## [[1]]
## [1] NA 8 12 10 15
## [[2]]
## [1] NA 6 2 7 24
Upvotes: 2
Reputation: 156
Use lapply
good <- list(c(NA,1,10,30,40), c(NA,3,4,5,10,20))
lapply(good, diff)
For the second part,
lapply(good, function(x)c(NA, diff(x)))
or
Map(c, NA, lapply(good, diff))
Hope that Helps.
Upvotes: 8