Reputation: 19405
Consider this simple dataframe
> data_frame(var1 = c(NA, 1 , NA),
+ var2 = c (NA, 3, NA))
# A tibble: 3 x 2
var1 var2
<dbl> <dbl>
1 NA NA
2 1 3
3 NA NA
I want to fill forward all the missing values for all columns in the dataframe. It seems to me that tidyr::fill()
can do that, but I am unable to make it work without specifying the columns one at a time.
> data_frame(var1 = c(NA, 1 , NA),
+ var2 = c (NA, 3, NA)) %>% tidyr::fill(.direction = 'down')
# A tibble: 3 x 2
var1 var2
<dbl> <dbl>
1 NA NA
2 1 3
3 NA NA
while entering the column name seems to work
> data_frame(var1 = c(NA, 1 , NA),
+ var2 = c (NA, 3, NA)) %>% tidyr::fill(var1, .direction = 'down')
# A tibble: 3 x 2
var1 var2
<dbl> <dbl>
1 NA NA
2 1 3
3 1 NA
what am I missing here? Thanks
Upvotes: 3
Views: 2338
Reputation: 43354
tidyr verbs accept dplyr::select
column specifications, so you can use everything()
:
library(tidyverse)
df <- data_frame(var1 = c(NA, 1 , NA),
var2 = c (NA, 3, NA))
df %>% fill(everything())
#> # A tibble: 3 x 2
#> var1 var2
#> <dbl> <dbl>
#> 1 NA NA
#> 2 1 3
#> 3 1 3
Upvotes: 12
Reputation: 887881
We can convert the column names to symbols with syms
and evaluate (!!!
)
d1 %>%
tidyr::fill(!!! rlang::syms(names(.)), .direction = 'down')
# A tibble: 3 x 2
# var1 var2
# <dbl> <dbl>
#1 NA NA
#2 1 3
#3 1 3
d1 <- data_frame(var1 = c(NA, 1 , NA), var2 = c (NA, 3, NA))
Upvotes: 2