how to move the NA to the end but without changing the sequence of other elements in a vector

hello, I am just wondering how to move the NA to the end but without changing the sequence of other elements in a vector, say I have a vector a<- (3,4,6,1,NA,2,NA,3), how can I "reorder " it to like (3,4,6,1,2,3,NA,NA)?

I would create a function for this. First use is.na() to find the NAs, then index and combine the non-NAs and NAs

a <- c(3, 4, 6, 1, NA, 2, NA, 3)

push_back_na <- function(x) {
  na <- is.na(x)
  c(x[!na], x[na])
}

push_back_na(a)
#> [1]  3  4  6  1  2  3 NA NA

Created on 2020-11-28 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.