R:向下填充多列

R: fill down multiple columns

我正在使用 tidyr 包中的 fill()。 fill(df, colname1, colname2, colname3) 工作正常,直到我找到一个包含 32 个变量的数据集。我应该如何在不键入每个名称的情况下填写所有列?

我试过:

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

并产生了以下错误:

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

当我们用 names 变量 select 时,我们可以使用 fill_

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

其他选项是

fill(df, everything())

但是,如果我们将 fillnames(df)) 一起使用,它会给出与 OP 显示的相同的错误

fill(df, names(df)[1])
#Error: All select() inputs must resolve to integer column positions.
#The following do not:
#*  names(df)[1]

数据

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)

zoo 的另一种选择,如果需要也可以向后填充。 在上面创建的示例中-

zoo::na.locf(df)

   col1 col2 col3
1     2    4    e
2     2    4    e
3     3    4    a
4     2    4    b
5     1    3    d
6     2    4    d
7     2    1    b
8     1    1    e
9     3    3    e
10    1    2    e
11    1    4    e
12    1    1    e
13    3    1    a
14    3    4    c
15    3    3    b
16    2    3    e
17    3    1    e
18    3    2    b
19    3    5    c
20    3    5    e

其中 df

   col1 col2 col3
1     2    4    e
2     2   NA    e
3     3    4    a
4     2    4    b
5     1    3    d
6     2    4 <NA>
7    NA    1    b
8     1   NA    e
9     3    3 <NA>
10    1    2    e
11    1    4    e
12   NA    1 <NA>
13    3   NA    a
14   NA    4    c
15    3    3    b
16    2    3    e
17    3    1    e
18   NA    2    b
19   NA    5    c
20    3    5    e

基于@akrun 的评论和数据,这里有另外两种使用 tidyr 的方法:

数据

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)

两个选项

#Specify column names
fill(df, c("col1", "col2"), .direction = "down")

#Specify range of columns
fill(df, c(col1:col3), .direction = "down")