【问题标题】:Cannot find (or select) imported CSV files找不到(或选择)导入的 CSV 文件
【发布时间】:2018-01-31 10:50:49
【问题描述】:

我已经阅读了许多 stackoverflow 问题和答案,但我仍然无法为我的问题找到解决方案:我想阅读大约 5 列。 80 个 .csv 文件到 R 中,无需手动输入所有代码,然后将这些文件合并到一个数据框中。然后,这个数据框需要与另一个具有相同列数的数据框合并。

所以我想用一个 for 循环来做这件事,这很有效,但我无法对其进行进一步的计算。我这样做了,我看到正在读取的文件:

filenames <- list.files(path = getwd(), pattern = "*.csv")
for (i in filenames) {
filepath <- file.path(getwd(), paste (i, sep = ""))
assign(i, fread(filepath, select = c(1,2,3,25,29), sep = ","))

我不知道如何访问刚刚读入的文件,即输入变量名(例如 df2)。以及如何将它们组合到一个数据框中,我可以将要与之组合的另一个数据框的列名分配给该数据框?

【问题讨论】:

  • 您可以使用rbind 在您读入每个新数据帧时合并它。

标签: r dataframe import


【解决方案1】:

嗯,你可以选择 CSV 文件。

filename <- file.choose()
data <- read.csv(filename, skip=1)
name <- basename(filename)

或者,硬编码路径。

# Read CSV into R
MyData <- read.csv(file="c:/your_path_here/Data.csv", header=TRUE, sep=",")

对于加入和合并,这里有一些很好的经验法则。

Inner join: merge(df1, df2) will work for these examples because R automatically joins the frames by common variable names, but you would most likely want to specify merge(df1, df2, by = "CustomerId") to make sure that you were matching on only the fields you desired. You can also use the by.x and by.y parameters if the matching variables have different names in the different data frames.

Outer join: merge(x = df1, y = df2, by = "CustomerId", all = TRUE)

Left outer: merge(x = df1, y = df2, by = "CustomerId", all.x = TRUE)

Right outer: merge(x = df1, y = df2, by = "CustomerId", all.y = TRUE)

Cross join: merge(x = df1, y = df2, by = NULL)

查看下面的链接了解更多详情。

How to join (merge) data frames (inner, outer, left, right)?

【讨论】:

    【解决方案2】:

    您可以从purrr 使用map_df

    filenames <- list.files(path = getwd(), pattern = "*.csv", full.names = TRUE)
    
    reader = function (x) {
     fread(x, select = c(1,2,3,25,29), sep = ",")
    }
    
    reading_files <- map_df(filenames, reader)
    

    map_df 将读入您的所有文件并使用非常高效的bind_rows 绑定它们

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多