本文介绍了R:填写多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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

解决方案

我们可以当我们选择用变量使用.

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)

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
解决方案

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)

这篇关于R:填写多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 03:42