【问题标题】:Selectively reading CSV file in r在 r 中选择性地读取 CSV 文件
【发布时间】:2016-06-09 14:44:25
【问题描述】:

我有一个 CSV 格式的大数据文件,我只需要导入其中的某些行。让我们将此大文件称为 A.csv。

我有另一个 csv 文件,即 B.csv,它有两列和几行。

现在我只需要从 A.csv 导入那些前两列值与某行的 B.csv 列值相同的数据行。所以,我在导入两个文件后尝试了这个

但这似乎需要永远

while(count<4632)
{
    count=count+1
    count2=0
    while(count2<17415)
    {
        count2=count 2+1
        if(B[count,1]==A[count2,1])
            dbase[count,]=A[count2,]
    }
}

请帮忙!!

【问题讨论】:

    标签: r select import rows


    【解决方案1】:

    您有两个嵌套的大循环,并且您正在动态增长一个向量。两者都对性能不利。尝试向量化这两个操作。

    例如:

    set.seed(123)
    dfA <- data.frame(
        a = sample(LETTERS, 10000, TRUE),
        b = sample(LETTERS[1:3], 10000, TRUE),
        c = rnorm( 10000 ),
        stringsAsFactors = FALSE
    )
    dfB <- data.frame(
        a = sample(LETTERS, 1000, TRUE),
        b = sample(LETTERS[1:3], 1000, TRUE),
        stringsAsFactors = FALSE
    )
    
    dfC <- dfA[ which( paste(dfA$a, dfA$b) %in% paste(dfB$a, dfB$a)), ]
    

    【讨论】:

    • 非常感谢!!这只是我在 stackoverflow 上的第二个问题,很高兴能得到帮助.. 继续加油..你们正在帮助我们成长!!
    【解决方案2】:

    也许我信息太少,但我会尽力回复...

    我认为您可以简单地将两个文件连接起来,只加载较小的文件。我会在 sqldf 包的帮助下做这样的事情:

    library(sqldf)
    
    tmp_csv <- "path/of/your/big/file.csv"
    
    # load your small file and make sure the two columns 
    # have the same name of the columns of the big file
    tmp_df <- read.csv("path/of/your/small/file.csv")
    
    # join the two dataset with a single sql query
    out_data <- read.csv2.sql(tmp_csv, sql = "select * from file join tmp_df using (Column1, Column2)", header = TRUE) 
    

    您可以使用 read.csv2.sql 或 read.csv.sql,具体取决于您的分隔符。 仔细检查列的名称,因为它是连接操作的基本部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 2014-09-15
      相关资源
      最近更新 更多