i am trying to simulate data using R.When i run the code below it creates an array with all the 10000 iterations from rexp. How can I have another vector within x to store the values from rpois(1,1,2) in code below.
set.seed(0)
system.time( x <- replicate(10000 ,rexp(rpois(1,1.2), rate=0.1)) )
Currently the first few output values from the code are.
[[1]]
[1] 2.669865 0 0 4.150295
[[2]]
[1] 0 4.150295
[[3]]
[1]2.669865 14.759684 4.150295 4.635850 11.200548
so in the revised code I would like to include count values from rpois(1,1.2)so the above output will be
[[1]]
[1] 4 2.669865 0 0 4.150295
[[2]]
[1] 2 0 4.150295
[[3]]
[1] 5 2.669865 14.759684 4.150295 4.635850 11.200548
We get the length
of each element in the list
with lengths
, concatenate ( c
) the corresponding element in the 'x' using Map
.
Map(c, lengths(x), x)
#[[1]]
#[1] 4.000000 2.669805 0.000000 0.000000 4.150925
#[[2]]
#[1] 2.000000 0.000000 4.150295
#[[3]]
#[1] 5.000000 2.669865 14.759684 4.150295 4.635800 11.200548
x <- list(c(2.669805, 0, 0, 4.150925), c(0, 4.150295),
c(2.669865, 14.759684, 4.150295, 4.6358, 11.200548))
here's a solution using lapply
:
li <- list(c(2.669865, 0, 0, 4.150925), c(0, 4.150295), c(2.669865, 14.759684, 4.150295, 4.635850, 11.200548))
lapply( li ,function(x){c(length(x),x)})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.