Problem 1 (solved)
How can I sort vector DoB
:
DoB <- c(NA, 9, NA, 2, 1, NA)
while keeping the NA
s in the same position?
I would like to get:
> DoB
[1] NA 1 NA 2 9 NA
I have tried this (borrowing from this answer)
NAs_index <- which(is.na(DoB))
DoB <- sort(DoB, na.last = NA)
for(i in 0:(length(NAs_index)-1))
DoB <- append(DoB, NA, after=(NAs_index[i+1]+i))
but
> DoB
[1] 1 NA 2 9 NA NA
Answer is
DoB[!is.na(DoB)] <- sort(DoB)
Thanks to @BigDataScientist and @akrun
Now, Problem 2
Say, I have a vector id
id <- 1:6
That I would also like to sort by the same principle, so that the values of id
are ordered according to order(DoB)
, but keeping the NA
s fixed in the same position?:
> id
[1] 1 5 3 4 2 6