【问题标题】:Only read selected columns只读取选定的列
【发布时间】:2016-07-17 05:22:53
【问题描述】:

谁能告诉我如何只读取以下数据中每年的前 6 个月(7 列),例如使用read.table()

Year   Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec   
2009   -41  -27  -25  -31  -31  -39  -25  -15  -30  -27  -21  -25
2010   -41  -27  -25  -31  -31  -39  -25  -15  -30  -27  -21  -25 
2011   -21  -27   -2   -6  -10  -32  -13  -12  -27  -30  -38  -29

【问题讨论】:

标签: r import r-faq


【解决方案1】:

假设数据在文件data.txt 中,您可以使用read.table()colClasses 参数来跳过列。这里前7列的数据是"integer",我们将剩下的6列设置为"NULL",表示应该跳过它们

> read.table("data.txt", colClasses = c(rep("integer", 7), rep("NULL", 6)), 
+            header = TRUE)
  Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27  -2  -6 -10 -32

根据实际数据类型,将"integer" 更改为?read.table 中详述的可接受类型之一。

data.txt 看起来像这样:

$ cat data.txt 
"Year" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
2009 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2010 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2011 -21 -27 -2 -6 -10 -32 -13 -12 -27 -30 -38 -29

并且是通过使用创建的

write.table(dat, file = "data.txt", row.names = FALSE)

dat 在哪里

dat <- structure(list(Year = 2009:2011, Jan = c(-41L, -41L, -21L), Feb = c(-27L, 
-27L, -27L), Mar = c(-25L, -25L, -2L), Apr = c(-31L, -31L, -6L
), May = c(-31L, -31L, -10L), Jun = c(-39L, -39L, -32L), Jul = c(-25L, 
-25L, -13L), Aug = c(-15L, -15L, -12L), Sep = c(-30L, -30L, -27L
), Oct = c(-27L, -27L, -30L), Nov = c(-21L, -21L, -38L), Dec = c(-25L, 
-25L, -29L)), .Names = c("Year", "Jan", "Feb", "Mar", "Apr", 
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = "data.frame",
row.names = c(NA, -3L))

如果事先不知道列数,实用函数count.fields 将读取文件并计算每行中的字段数。

## returns a vector equal to the number of lines in the file
count.fields("data.txt", sep = "\t")
## returns the maximum to set colClasses
max(count.fields("data.txt", sep = "\t"))

【讨论】:

  • @Benjamin 使用参数nrows 从文件中读取前几行。然后计算出使用ncol() 的列数,否则您想计算出要读取/忽略的列数。然后使用此信息阅读完整文件。
  • ??如果您不知道列数,您将如何确定它而不阅读它来推断有多少?
  • @BlueMagister 感谢count.fields() 的编辑和提及,它使我在 cmets 中建议的过程自动化。
  • @LéoLéopoldHertz준영 不,我不确定这样的事情对于数据框中的行 classes 是如何工作的,而每一列可能是不同的类型,根据定义,每一行都是不受约束的。您需要在导入时过滤掉空白行等。
  • @rmf 你可以传递count.fields() 一个文本连接,所以,使用txt &lt;- readLines(....) 读取行的一些子集,然后创建到读取行con &lt;- textConnection(txt) 的连接,然后执行@987654342 @。如果有标题行,请务必在count.fields() 中使用skip 跳过标题行;您不能使用 readLines() 跳过文件中的行。
【解决方案2】:

您也可以使用 JDBC 来实现这一点。让我们创建一个示例 csv 文件。

write.table(x=mtcars, file="mtcars.csv", sep=",", row.names=F, col.names=T) # create example csv file

从此链接下载并保存 CSV JDBC 驱动程序:http://sourceforge.net/projects/csvjdbc/files/latest/download

> library(RJDBC)

> path.to.jdbc.driver <- "jdbc//csvjdbc-1.0-18.jar"
> drv <- JDBC("org.relique.jdbc.csv.CsvDriver", path.to.jdbc.driver)
> conn <- dbConnect(drv, sprintf("jdbc:relique:csv:%s", getwd()))

> head(dbGetQuery(conn, "select * from mtcars"), 3)
   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1   21   6  160 110  3.9  2.62 16.46  0  1    4    4
2   21   6  160 110  3.9 2.875 17.02  0  1    4    4
3 22.8   4  108  93 3.85  2.32 18.61  1  1    4    1

> head(dbGetQuery(conn, "select mpg, gear from mtcars"), 3)
   MPG GEAR
1   21    4
2   21    4
3 22.8    4

【讨论】:

    【解决方案3】:

    要从数据集中读取一组特定的列,还有其他几个选项:

    1) 使用fread来自data.table-package:

    您可以使用来自data.table 包的fread 中的select 参数指定所需的列。您可以使用包含列名或列号的向量来指定列。

    对于示例数据集:

    library(data.table)
    dat <- fread("data.txt", select = c("Year","Jan","Feb","Mar","Apr","May","Jun"))
    dat <- fread("data.txt", select = c(1:7))
    

    或者,您可以使用drop 参数来指示不应读取哪些列:

    dat <- fread("data.txt", drop = c("Jul","Aug","Sep","Oct","Nov","Dec"))
    dat <- fread("data.txt", drop = c(8:13))
    

    所有结果:

    > data
      Year Jan Feb Mar Apr May Jun
    1 2009 -41 -27 -25 -31 -31 -39
    2 2010 -41 -27 -25 -31 -31 -39
    3 2011 -21 -27  -2  -6 -10 -32
    

    更新:当您不希望 fread 返回 data.table 时,请使用 data.table = FALSE 参数,例如:fread("data.txt", select = c(1:7), data.table = FALSE)

    2) 使用来自sqldf-package 的read.csv.sql

    另一种选择是sqldf 包中的read.csv.sql 函数:

    library(sqldf)
    dat <- read.csv.sql("data.txt",
                        sql = "select Year,Jan,Feb,Mar,Apr,May,Jun from file",
                        sep = "\t")
    

    3) 使用 readr-package 中的 read_*-functions:

    library(readr)
    dat <- read_table("data.txt",
                      col_types = cols_only(Year = 'i', Jan = 'i', Feb = 'i', Mar = 'i',
                                            Apr = 'i', May = 'i', Jun = 'i'))
    dat <- read_table("data.txt",
                      col_types = list(Jul = col_skip(), Aug = col_skip(), Sep = col_skip(),
                                       Oct = col_skip(), Nov = col_skip(), Dec = col_skip()))
    dat <- read_table("data.txt", col_types = 'iiiiiii______')
    

    从文档中对col_types中使用的字符的解释:

    每个字符代表一列:c = 字符,i = 整数,n = 数字,d = 双精度,l = 逻辑,D = 日期,T = 日期时间,t = 时间,? = 猜测,或 _/- 跳过该列

    【讨论】:

    • 但是,fread 不支持压缩文件。大文件通常会被压缩。
    • feature request 用于在fread 中启用此功能。值得注意的是fread 很可能会比read.table 读取压缩文件快得多。 See here for an example.
    • 一些未压缩的文件太大。例如。我正在处理 1000 个基因组文件。它们可以是 60 GB 未压缩。
    • 你可能知道,R 读取内存中的数据。无论您阅读压缩文件还是解压缩文件,都不会影响内存中结果数据的大小。如果你有 60GB 的文件,read.table 不会救你。在这种情况下,您可能需要查看ff-package。
    • @Deleet 您可以使用fread 读取大型压缩文件,如下所示:fread("gunzip -c data.txt.gz", drop = c(8:13))
    【解决方案4】:

    你这样做:

    df = read.table("file.txt", nrows=1, header=TRUE, sep="\t", stringsAsFactors=FALSE)
    colClasses = as.list(apply(df, 2, class))
    needCols = c("Year", "Jan", "Feb", "Mar", "Apr", "May", "Jun")
    colClasses[!names(colClasses) %in% needCols] = list(NULL)
    df = read.table("file.txt", header=TRUE, colClasses=colClasses, sep="\t", stringsAsFactors=FALSE)
    

    【讨论】:

      【解决方案5】:

      vroom package 提供了一种在导入期间按名称选择/删除列的“整洁”方法。文档:https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection

      列选择(col_select)

      vroom 参数“col_select”使选择要保留(或省略)的列更加直接。 col_select 的接口与 dplyr::select() 相同。

      按名称选择列
      data <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
      #> Observations: 336,776
      #> Variables: 3
      #> chr [1]: tailnum
      #> dbl [2]: year, flight
      #> 
      #> Call `spec()` for a copy-pastable column specification
      #> Specify the column types with `col_types` to quiet this message
      
      按名称删除列
      data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
      #> Observations: 336,776
      #> Variables: 13
      #> chr [4]: carrier, tailnum, origin, dest
      #> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
      #> 
      #> Call `spec()` for a copy-pastable column specification
      #> Specify the column types with `col_types` to quiet this message
      Use the selection helpers
      data <- vroom("flights.tsv", col_select = ends_with("time"))
      #> Observations: 336,776
      #> Variables: 5
      #> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
      #> 
      #> Call `spec()` for a copy-pastable column specification
      #> Specify the column types with `col_types` to quiet this message
      
      或按名称重命名列
      data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
      #> Observations: 336,776
      #> Variables: 19
      #> chr  [ 4]: carrier, tailnum, origin, dest
      #> dbl  [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
      #> dttm [ 1]: time_hour
      #> 
      #> Call `spec()` for a copy-pastable column specification
      #> Specify the column types with `col_types` to quiet this message
      data
      #> # A tibble: 336,776 x 19
      #>    plane  year month   day dep_time sched_dep_time dep_delay arr_time
      #>    <chr> <dbl> <dbl> <dbl>    <dbl>          <dbl>     <dbl>    <dbl>
      #>  1 N142…  2013     1     1      517            515         2      830
      #>  2 N242…  2013     1     1      533            529         4      850
      #>  3 N619…  2013     1     1      542            540         2      923
      #>  4 N804…  2013     1     1      544            545        -1     1004
      #>  5 N668…  2013     1     1      554            600        -6      812
      #>  6 N394…  2013     1     1      554            558        -4      740
      #>  7 N516…  2013     1     1      555            600        -5      913
      #>  8 N829…  2013     1     1      557            600        -3      709
      #>  9 N593…  2013     1     1      557            600        -3      838
      #> 10 N3AL…  2013     1     1      558            600        -2      753
      #> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
      #> #   arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
      #> #   dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
      #> #   time_hour <dttm>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多