2017-04-25 57 views
1

我有一系列的數據,它看起來像R讀取文件的名字,並把它變成變量

sale20160101.txt, 

sales20160102.txt,..., 

sales20171231. 

現在我要讀所有這些,結合起來,但它也需要一個日期變量 幫我確定它們的發生時間,因此日期變量將爲 20160101,20160102,...,20161231。

我的想法是:

分割成文件名+銷售「時間」每當我根據數據長度

cbind數據和時間的讀取數量

重複的時間。

thx很多。

回答

1

我們可以用freadrbindlistdata.table

library(data.table) 
#find the files that have names starting as 'sales' followed by numbers 
#and have .txt extension 
files <- list.files(pattern = "^sale.*\\d+\\.txt", full.names = TRUE) 

#get the dates 
dates <- readr::parse_number(basename(files)) 

#read the files into a list and rbind it 
dt <- rbindlist(setNames(lapply(files, fread), dates), idcol = 'date') 
+1

THX做到這一點,它的工作原理完美 – changjx

1

我通常會做如下的變化:

# find the files 
ls <- list.files(pattern = '^sales') 
# Get the dates 
dates <- gsub('sales', '', tools::file_path_sans_ext(ls)) 

# read in the data 
dfs <- lapply(ls, read.table) 
# match the dates 
names(dfs) <- dates 

# bind all data together and include the date as a column 
df <- dplyr::bind_rows(dfs, .id = 'date') 
相關問題