【问题标题】:Check table's header is as expected when read.csv in R在 R 中 read.csv 时检查表的标题是否符合预期
【发布时间】:2018-03-05 16:19:20
【问题描述】:

我正在尝试在我的 R 脚本中插入一个检查步骤,以确定我正在读取的 CSV 表的结构是否符合预期。 查看详细信息: table.csv 具有以下列名: [1] "A","B","C","D"

这个文件是由其他人生成的,因此我想在我的脚本开始时确保列名和列的数量/顺序没有改变。

我尝试执行以下操作:

    #dataframes to import
    df_table <- read.csv('table.csv')

    #define correct structure of file
    Correct_Columns <- c('A','B','C','D')
    #read current structure of table
    Current_Columns <- colnames(df_table)

    #Check whether CSV was correctly imported from Source
    if(Current_Columns != Correct_Columns)

    {
    # if structure has changed, stop the script. 
    stop('Imported CSV has a different structure, please review export from Source.')
    } 
    #if not, continue with the rest of the script...

提前感谢您的帮助!

【问题讨论】:

  • 我想你想要if(any(Current_Columns != Correct_Columns))。我假设您之前遇到了一些错误?包含有关您的解决方案为何不起作用的信息会有所帮助。

标签: r


【解决方案1】:

使用base R,我建议你看看all.equal()identical()any()

请看下面的例子:

a <- c(1,2)
b <- c(1,2)
c <- c(1,2)
d <- c(1,2)
df <- data.frame(a,b,c,d)

names.df <- colnames(df)
names.check <- c("a","b","c","d")

!all.equal(names.df,names.check)
# [1] FALSE

!identical(names.df,names.check)
# [1] FALSE

any(names.df!=names.check)
# [1] FALSE

以下,您的代码可以修改如下:

if(!all.equal(Current_Columns,Correct_Columns))
{
# call your stop statement here
} 

您的代码可能会引发警告,因为 Current_Columns!=Correct_Columns 将比较向量的所有条目(即在控制台上单独运行 Current_Columns!=Correct_Columns 将返回具有 TRUE/FALSE 值的向量)。

相反,all.equal()identical() 将比较整个向量,同时将它们视为对象。

为了完整起见,请注意all.equal()identical() 之间的细微差别。在您的情况下,您使用哪一个并不重要,但在处理数值向量时它会变得很重要。请参阅here 了解更多信息。

【讨论】:

  • 非常感谢,它就像一个魅力!现在唯一的问题是,当我从主脚本中调用脚本时它不起作用: > #### 运行脚本 #### > source('location/...[TRUNCATED] Error in eval(ei, envir ) : 导入的 CSV 具有不同的结构,请查看从 Source 导出。
  • 差点忘了,如果我自己运行相同的脚本,它会起作用,并且 IF 实例不会触发,因为文件结构实际上是相同的。只有当我从主脚本运行它时,它才会通过 IF 测试...
  • 我猜你的主脚本的代码对于查看错误在哪里是必要的。我的第一个猜测是运行主脚本时您的工作目录是不同的,因此会加载不同的“table.csv”文件。但这只是一个疯狂的猜测。
【解决方案2】:

使用 data.table 的快速方法:

library(data.table)
DT <- fread("table.csv")
Correct_Columns <- c('A','B','C','D')
Current_Columns <- colnames(df_table)

检查成对匹配是否有假:

if(F %in% Current_Columns == Correct_Columns){
  stop('Imported CSV has a different structure, please review export from Source.')
} 

}

【讨论】:

    猜你喜欢
    • 2019-12-06
    • 2012-08-12
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多