Filling NA row values with nearest right side row value in R

前端 未结 2 1528
情话喂你
情话喂你 2020-12-21 18:54

I want to convert the given dataframe from

             c1     c2   c3   c4    c5
    VEG PUFF     12     78.43
CHICKEN PUFF &l         


        
2条回答
  •  一生所求
    2020-12-21 19:38

    Update

    As there was lot of confusion on the expected output, updating the answer as suggested by @DavidArenburg using a tidyverse solution

    library(dplyr)
    library(tidyr)
    df %>%
      add_rownames() %>%
      gather(variable, value, -rowname) %>%
      filter(!is.na(value)) %>%
      group_by(rowname) %>%
      mutate(indx = row_number()) %>%
      select(-variable) %>%
      spread(indx, value)
    
    #        rowname   `1`   `2`
    #*          
    #1 BAKERY_Total    28 84.04
    #2 CHICKEN_PUFF    16 88.24
    #3     VEG_PUFF    12 78.43
    

    Another solution could be

    library(data.table)
    temp <- apply(df, 1, function(x) data.frame(matrix(x[!is.na(x)], nrow = 1)))
    rbindlist(temp, fill = T)
    

    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 row

    We can use na.locf with fromLast set as TRUE

    t(apply(df, 1, function(x) na.locf(x, fromLast = T, na.rm = F)))
    
    
    #             c1 c2    c3    c4    c5
    #VEG_PUFF     12 12 78.43 78.43 78.43
    #CHICKEN_PUFF 16 16 88.24 88.24    NA
    #BAKERY_Total 28 28 28.00 84.04 84.04
    

提交回复
热议问题