簡體   English   中英

R從多個csv中讀取某些列值

[英]R reading certain column values from multiple csv's

我的文件夾中有多個 csv 文件,它們遵循以下語法:“Sales-”Month”-“Year”

例如:

Sales-APR-2019.csv 
Sales-APR-2020.csv 
Sales-MAR-2019.csv 
Sales-DEC-2019.csv 

我在 R 中的任務是提取 2019 年全年的某些產品。我將我的函數設置如下:

myfiles = list.files( pattern="SALES-EXTRACT-...-2019-NEW.csv", full.names=TRUE) \
file <- ldply(myfiles, read_csv)

這是問題,文件很大,所以我不想將它們全部加載到 R 中。如果我有我需要的文章,例如 1、2、3、4 和 5,我如何指定只獲取列的位置值等於那些文章?

最后,我想省略讀取所有 csv 的第一行,其中 1 個文件將被讀取為:\\

file <- read.csv("SALES--APR-2019.csv",header = TRUE)[-1,]

讀取所有文件時,我可以在代碼中的何處指定 [-1,] ?

vroom 包提供了一種在導入期間按名稱選擇/刪除列的“整潔”方法。 文檔: 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

要加載多個文件並選擇特定列並跳過第一行:

files <- fs::dir_ls(glob = "SALES*2019.csv")
data <- vroom(files, col_select = c(article_1, article_2, article_3, etc), skip = 1)

如果文章信息存儲在每個文件中名為article的列article ,您可以嘗試-

library(tidyverse)

keep_articles <- 1:5
myfiles = list.files(pattern="SALES-.*-2019.csv", full.names=TRUE)

data <- map_df(myfiles, ~read_csv(.x) %>% 
                  slice(-1) %>%
                  filter(article %in% keep_articles), .id = 'file')

data將有一個組合數據keep_articles讀取所有 csv 並為keep_articles保留行。 還將創建一個額外的file列來區分不同文件的行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM