How do I run code as cumulative numbers?
This is my code
x <- runif(50)
y <- 10
cumsum(x) <= y
It only returns logical (boolean)
[1] TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE
if I try to correct this by adding as.numeric or as.integer it returns
[1] 1 1 1 1 0 0 0 0 0 0
The problem with your code is you are comparing if the cumsum(x)
is <=
y
. And whenever you do these kinds of comparisons you will get a logical vector.
But if you are looking for items that are smaller than y
you can do the following:
x <- runif(50)
y <- 10
idx <- which(cumsum(x) <= y)
x[idx]
The idx
stores the indices at which the condition is matched i.e. cumsum(x) <= y
. And to print the numbers at those indices you can use x[idx]
.
The output will look like this:
[1] 0.95362053 0.09553108 0.82016689 0.69883212 0.35495891 0.16966706
[7] 0.15281253 0.16532772 0.81920233 0.82249972 0.30146590 0.69536763
[13] 0.32764723 0.40601504 0.70189321 0.16597773 0.25304473 0.41667253
[19] 0.52499118 0.27216339 0.27347937