InspectorSands
InspectorSands

Reputation: 2929

Sort vector keeping NAs position in R

Problem 1 (solved)

How can I sort vector DoB:

DoB <- c(NA, 9, NA, 2, 1, NA)

while keeping the NAs 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 NAs fixed in the same position?:

> id
[1] 1 5 3 4 2 6

Upvotes: 0

Views: 364

Answers (2)

Tonio Liebrand
Tonio Liebrand

Reputation: 17689

You could do:

DoB[!is.na(DoB)] <- sort(DoB)

Edit: Concerning the follow up question in the comments:

You can use order() for that and take care of the NAs with the na.last parameter,..

data <- data.frame(DoB = c(NA, 9, NA, 2, 1, NA), id = 1:6)
data$id[!is.na(data$DoB)] <- order(data$DoB, na.last = NA)
data$DoB[!is.na(data$DoB)] <- sort(data$DoB)

Upvotes: 2

akrun
akrun

Reputation: 887088

We create a logical index and then do the sort

i1 <- is.na(DoB)
DoB[!i1] <- sort(DoB[!i1])
DoB
#[1] NA  1 NA  2  9 NA

Upvotes: 2

Related Questions