0

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
Community
  • 1
  • 1
InspectorSands
  • 2,859
  • 1
  • 18
  • 33

2 Answers2

2

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
akrun
  • 874,273
  • 37
  • 540
  • 662
2

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)
Tonio Liebrand
  • 17,189
  • 4
  • 39
  • 59
  • Can I expand a bit: what if I wanted to order a second vector (id = 1:6) by the same principle (to have `id` be 1 5 3 4 2 6)? – InspectorSands May 12 '17 at 17:22
  • you mean: `id[c(1,5,3,4,2,6)]` ? (however, we shouldnt get too unrelated from the original question, in the follow up comments :) ) – Tonio Liebrand May 12 '17 at 17:39
  • I edited the question to make this second part clearer, I didn't thin kit was worth opening a second question, but I can also do that if it would be more appropriate. My Problem 2 is basically, how can I use `order` to return a vector of the ordered indices while keeping the `NA`s fixed in the same position? – InspectorSands May 12 '17 at 17:48
  • you are right the questions belong "together",...hope the edit helps! – Tonio Liebrand May 12 '17 at 18:03
  • awesome, you're a :star: ! – InspectorSands May 12 '17 at 18:08