2

How i can move all the NA to the top of the column F of the DF data.frame. I don't want to move its corresponding Dates, just the NA to the top of column of F.

set.seed(1500)
DF <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2003-12-31"), by="day"),
                      A = runif(1095, 0,10),
                      D = runif(1095,5,15),
                      F = c(runif(1000,3,5), rep(NA, 95)))
Edward
  • 10,360
  • 2
  • 11
  • 26
Hydro
  • 1,057
  • 12
  • 25

3 Answers3

3

You can use order with is.na to bring NA to the top.

DF$F <- DF$F[order(!is.na(DF$F))]

Or you use only is.na one as it is and one as negation.

i <- is.na(DF$F)
DF$F <- c(DF$F[i], DF$F[!i])
GKi
  • 37,245
  • 2
  • 26
  • 48
1

Perhaps, something like this?

DF$F <- c(rep(NA, sum(is.na(DF$F))), na.omit(DF$F))

Add all the NA's first and then append all the non-NA values.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Assuming all NA's are at the end, we can shift:

x <- c(1:5, c(NA, NA))
x
# [1]  1  2  3  4  5 NA NA

data.table::shift(x, sum(is.na(x)))
# [1] NA NA  1  2  3  4  5

Or as column F is not related to other columns, just reverse it:

rev(x)
# [1] NA NA  5  4  3  2  1
zx8754
  • 52,746
  • 12
  • 114
  • 209