I want to convert the given dataframe from
c1 c2 c3 c4 c5
VEG PUFF <NA> 12 <NA> <NA> 78.43
CHICKEN PUFF <NA> 16 <NA> 88.24 <NA>
BAKERY Total <NA> <NA> 28 <NA> 84.04
to
c1 c2
VEG PUFF 12 78.43
CHICKEN PUFF 16 88.24
BAKERY Total 28 84.04
I tried two methods but i didnt get accurate results it is sometimes taking left side row value
step1 <- t(na.locf(t(df), fromLast=T))
step2 <- t(na.locf(t(step1), fromLast=F))
library(dplyr)
MyReplace = function(data) {data %>% t %>% na.locf(.,,T) %>% na.locf %>% t
Update
As there was lot of confusion on the expected output, updating the answer as suggested by @DavidArenburg using a
tidyverse
solutionAnother solution could be
Previous Answer
If I have understand you correctly, you are trying to replace
NA
values in a row with the latest non-NA value in the same rowWe can use
na.locf
withfromLast
set asTRUE