2017-04-25 79 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') 
相关问题