0

I like to fill in missing values for some variable based on its value paired with a matching index. Example (First col is the index; second col is the values).

mat <- cbind(c(1,1,2,2,3,3,4,4,4), c(4.3, NA, 2.4, NA, 3.8, NA, 1.2, NA, NA))

newmat <- cbind(c(1,1,2,2,3,3,4,4,4), c(4.3, 4.3, 2.4, 2.4, 3.8, 3.8, 1.2, 1.2, 1.2))

enter image description here

randmlaber
  • 109
  • 1
  • 1
  • 6

1 Answers1

1

We can use fill

library(dplyr)
library(tidyr)
mat %>% 
  as_tibble %>% 
  group_by(V1) %>% 
  fill(V2, .direction = 'updown')
akrun
  • 874,273
  • 37
  • 540
  • 662