Lalochezia
Lalochezia

Reputation: 497

Filling an empty vector with values relative to the first value in the vector

I have a vector:

sample.vector
      1
      1
      0
      0
      14
      1
      1
      0
      1
      12

I created a second vector with the following code:

second.vector <- c(1, rep(NA, length(sample.vector)))

Which made this:

second.vector
      1
      NA
      NA
      NA
      NA
      NA
      NA
      NA
      NA
      NA
      NA

I want to populate second.vector such that the NAs are replaced with 0 + the value in the row above it (i.e. the 1 in the first row of second vector) if sample.vector < 3 or 1 + the value in the row above it (i.e. whatever that value may be) if sample.vector > 3.

In other words:

R, I want you to look at row[n] in sample.vector. If the value is less than three, I want you to replace the NA in second.vector with the value above that NA. If the value in row[n] is greater than 3, I want you to fill the NA in second.vector with the value above that NA, but add 1 to it.

Do this for every row within sample.vector so that every NA in second.vector is replaced with values.

So the vector that I'm hoping to get is:

second.vector
      1
      1
      1
      1
      1
      2
      2
      2
      2
      2
      3

I've tried this:

second.vector[2:length(second.vector)] <- 
    ifelse(sample.vector[1:length(sample.vector)] > 3, 
    second.vector[1:length(second.vector)]+1, 
    second.vector[1:length(second.vector)]+0)

But it just gives the second row of second.vector a 1, rather than filling up the entire vector.

Any thoughts on how to do this?

Upvotes: 2

Views: 459

Answers (1)

cuttlefish44
cuttlefish44

Reputation: 6786

cumsum() returns cumulative sums. For example, cumsum(c(3, 7, 1)) is [1] 3 10 11

sample.vector <- c(1,1,0,0,14,1,1,0,1,12)
library(dplyr) # just to explain

(sample.vector > 3) %>% # [1] FALSE FALSE FALSE FALSE TRUE ...
  as.numeric()  %>%     # [1] 0 0 0 0 1 ...  # but this line is unnecessary, thanks @Pierre Lafortune
    cumsum()  %>%       # [1] 0 0 0 0 1 1 1 1 1 2  # do cumulative sums
      + 1               # [1] 1 1 1 1 2 2 2 2 2 3  # what you want

# summarizing the above,
cumsum(sample.vector > 3) + 1

Upvotes: 2

Related Questions