0

Is it possible to "fill up" NA values based on a condition in two other columns?

A similar answer is found here: Replace missing values (NA) with most recent non-NA by group

This question is different because I need the fill up to be based on the values of another column and the value above the value in said column. Explanation below.

I have a dataframe and I need something that looks at the value above and the value beside and the value above that to evaluate. The process should go like this: x = value that is not null.

if value above x is null and

value beside x is the same as the value above the value of x then

fill up.

Here is some example code from mtcars

mtcars1 <- as_tibble(mtcars)

mtcars1 <- mtcars1 %>%
  select(cyl, mpg, disp, hp) %>%
  group_by(cyl) %>%
  arrange(cyl, disp)


ex <- rep("NA", length(mtcars1$cyl))

mtcars1$ex=ex 

mtcars1$ex <- if_else(mtcars$cyl = 4 & mtcars$disp > 100, ex==31.4, ex)

mtcars1$ex <- sapply(mtcars1, function(x) ifelse((mtcars1$cyl <= 4 && 
mtcars$disp > 100), 23.5, "NA"))

See the picture below. I want 23.5 to fill up until the values in the "cyl" column change. So,

if value above is NULL()

and cyl value = cyl value above,

fill up.

enter image description here

Is this possible in R?

Jordan
  • 1,415
  • 3
  • 18
  • 44

0 Answers0