I know there were a lot of answers already here to shift the non-NA values to the left, rowwise. But all of these will take me forever to do this. Is there a fastest way to perform this task? Example:
#from
X1 X2 X3 X4 X5 X6 X7
NA NA AB NA AD AE AF
NA NA NA AG NA AI AJ
NA AK AL AM NA AO AP
NA NA AQ NA AS AT NA
AV AW AX AY AZ NA BB
#to
X1 X2 X3 X4 X5 X6 X7
AB AD AE AF NA NA NA
AG AI AJ NA NA NA NA
AK AL AM AO AP NA NA
AQ AS AT AU NA NA NA
AV AW AX AY AZ BB NA
Using apply
and/or for
loops take a lot of time. For context, I have a dataframe with 340K rows and 67 columns and it will take me 18+ hours to do the job if I ran the following:
for (i in 1:nrow(df)) {
Temp <- unlist(df[i,])
ndf[i,] <- t(c(Temp[!is.na(Temp)],Temp[is.na(Temp)]))
}
Other suggested solutions in the other posts seems to be similar to this one, so I would also expect to take a long time.
I've also tried following code:
ndf <- na_move(df) #from package: dedupewider
But it seems that the it hasn't done the job for the last 3 columns, as follows:
#to
X1 X2 X3 X4 X5 X6 X7
AB NA NA NA AD AE AF
AG NA NA NA NA AI AJ
AK AL AM NA NA AO AP
AQ NA NA NA AS AT NA
AV AW AX AY AZ NA BB
Hoping for a solution for this. Thank you very much!