【问题标题】:Import a specific column of a CSV in R在 R 中导入 CSV 的特定列
【发布时间】:2021-09-01 04:21:04
【问题描述】:

我们已经知道如何在 R 中选择数据框的列。

但是如果我们想选择我们想在环境中导入 csv 的哪些列呢?

例如,如果我有一个四列用空格分隔的 csv:

IEAL <- read.csv(file="/Directory/ieal.csv", sep=" ")

如何选择只导入第二列?

【问题讨论】:

  • IEAL &lt;- read.csv(file="/Directory/ieal.csv", sep=" ")[, 2]。虽然在这里您要导入所有内容,然后选择第二列。
  • 您可以使用 vroom 包指定要导入的列:tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection
  • 您可以使用data.table::fread("/Directory/ieal.csv", select=...),其中... 是要选择的列的字符向量或列号的向量。

标签: r csv import


【解决方案1】:

您可以从包sqldf 中带有read.csv.sql 的文件中选择一列。

首先,创建一个文件。在这种情况下,它是一个 CSV 文件,以逗号作为列分隔符。

write.csv(iris, "iris.csv", quote = FALSE, row.names = FALSE)

现在只阅读第二列。

library(sqldf)


iris2 <- read.csv.sql(
  file = "iris.csv",
  sql = "select `Sepal.Width` from file")

str(iris2)
#'data.frame':  150 obs. of  1 variable:
# $ Sepal.Width: num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...

如果分隔符是空格,设置sep = " "

iris3 <- read.csv.sql(
  file = "iris.txt",
  sep = " ",
  sql = "select `Sepal.Width` from file")

identical(iris2, iris3)
#[1] TRUE

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 2015-12-13
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多