0

I found the script below for cleaning NAs and left-shifting rows. Here's the discussion: Dropping all left NAs in a dataframe and left shifting the cleaned rows

for (i in 1:nrow(dat)) {

if (is.na(dat[i,1])==TRUE) {
    dat1 <- dat[i, min(which(!is.na(dat[i,]))):length(dat[i,])]
    dat[i,]  <- data.frame( dat1, t(rep(NA, ncol(dat)-length(dat1))) )
}

}

dat

I'd like to clean a varying number of NAs from the top of columns and then upshift the cleaned columns. Is there any chance someone could help me modify the above script for that purpose?

Community
  • 1
  • 1
Hedgehog
  • 15
  • 4

1 Answers1

0

Like this?

dat <- as.data.frame(rbind(c(NA,NA,1,3,5,NA,NA,NA), c(NA,1:3,6:8,NA), c(1:7,NA)))
dat
#   V1 V2 V3 V4 V5 V6 V7 V8
# 1 NA NA  1  3  5 NA NA NA
# 2 NA  1  2  3  6  7  8 NA
# 3  1  2  3  4  5  6  7 NA

dat[] <- apply(dat, 2, function(x) `length<-`(na.omit(x), length(x)))
dat
#   V1 V2 V3 V4 V5 V6 V7 V8
# 1  1  1  1  3  5  7  8 NA
# 2 NA  2  2  3  6  6  7 NA
# 3 NA NA  3  4  5 NA NA NA
KFB
  • 3,501
  • 3
  • 15
  • 18