Search code examples
rfilltidyr

R: fill down multiple columns


I'm using fill() from the tidyr package. fill(df, colname1, colname2, colname3) works fine, until I found a dataset with 32 variables. How should I fill down all columns without typing each name?

I've tried:

fill(df,colnames(df)),
fill(df,1:32), 
fill(df,colname1:colname32). 

and produced the following errors:

Error: All select() inputs must resolve to integer column positions.
The following do not:
*  colnames(df1)

Error: tinyformat: Not enough conversion specifiers in format string

Error: tinyformat: Not enough conversion specifiers in format string

Solution

  • We can use fill_ when we select variables with names.

    library(tidyr)# using tidyr_0.4.1.9000
    res <- 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)