How to filter NA's in each column of dataframe in R

Viewed 82

I have a tibble as

DF_TEST = tibble('country'=c('a','a','a','a'),
'id'=c(3,3,3,3),
'shop'=c('dmart','dmart','dmart','dmart'),
'beef'=c(23,NA,NA,NA),
'eggs'=c(NA,33,NA,NA),
'fork'=c(NA,NA,10,NA),
'veg'=c(NA,NA,NA,40))

Here it's output as,

  country    id shop   beef  eggs  fork   veg
  <chr>   <dbl> <chr> <dbl> <dbl> <dbl> <dbl>
1 a           3 dmart    23    NA    NA    NA
2 a           3 dmart    NA    33    NA    NA
3 a           3 dmart    NA    NA    10    NA
4 a           3 dmart    NA    NA    NA    40

I would like to convert this tibble as below by keeping a side NA's

  country    id shop   beef  eggs  fork   veg
  <chr>   <dbl> <chr> <dbl> <dbl> <dbl> <dbl>
1 a           3 dmart    23    33    10    40

Could you please write your suggestions how to get it done ?.

2 Answers

One dplyr solution could be:

DF_TEST %>%
 group_by_at(1:3) %>%
 summarise_all(~ first(na.omit(.)))

  country    id shop   beef  eggs  fork   veg
  <chr>   <dbl> <chr> <dbl> <dbl> <dbl> <dbl>
1 a           3 dmart    23    33    10    40

Base R one liner:

aggregate(.~country+id+shop, replace(DF_TEST, is.na(DF_TEST), as.numeric(0)), FUN = sum)
Related