R: fill down multiple columns
We can use fill_
when we select variables with names
.
library(tidyr)# using tidyr_0.4.1.9000res <- fill_(df, names(df))head(res)# col1 col2 col3#1 1 NA b#2 1 3 b#3 2 4 a#4 2 4 a#5 2 1 a#6 3 4 a
Other option would be
fill(df, everything())
However, if we use fill
with names(df))
, it will give the same error as the OP showed
fill(df, names(df)[1])#Error: All select() inputs must resolve to integer column positions.#The following do not:#* names(df)[1]
data
set.seed(24) df <- data.frame(col1= sample(c(NA, 1:3), 20, replace=TRUE), col2 = sample(c(NA, 1:5), 20, replace=TRUE), col3 = sample(c(NA, letters[1:5]), 20, replace=TRUE), stringsAsFactors=FALSE)
Another alternative with package zoo
which can also fill backwards if desired.On the sample created above-
zoo::na.locf(df) col1 col2 col31 2 4 e2 2 4 e3 3 4 a4 2 4 b5 1 3 d6 2 4 d7 2 1 b8 1 1 e9 3 3 e10 1 2 e11 1 4 e12 1 1 e13 3 1 a14 3 4 c15 3 3 b16 2 3 e17 3 1 e18 3 2 b19 3 5 c20 3 5 e
where df
is
col1 col2 col31 2 4 e2 2 NA e3 3 4 a4 2 4 b5 1 3 d6 2 4 <NA>7 NA 1 b8 1 NA e9 3 3 <NA>10 1 2 e11 1 4 e12 NA 1 <NA>13 3 NA a14 NA 4 c15 3 3 b16 2 3 e17 3 1 e18 NA 2 b19 NA 5 c20 3 5 e
Building off @akrun's comment and data, here are two other ways using the tidyr:
Data
set.seed(24)df <- data.frame(col1= sample(c(NA, 1:3), 20, replace=TRUE), col2 = sample(c(NA, 1:5), 20, replace=TRUE), col3 = sample(c(NA, letters[1:5]), 20, replace=TRUE), stringsAsFactors=FALSE)
Two Options
#Specify column namesfill(df, c("col1", "col2"), .direction = "down")#Specify range of columnsfill(df, c(col1:col3), .direction = "down")