我有许多txt文件,它们在分隔为;的列中包含相同类型的数值数据。但是,有些文件有带有空格的列头,而有些没有(由不同的人创建)。有些有我不想要的额外栏目。
例如,一个文件可能有一个标题,如:
ASomeName; BSomeName; C(someName%) 而另一个文件头可能是
A Some Name; B Some Name; C(someName%); D some name在调用"read“命令之前,如何清除名称中的空格?
#These are the files I have
filenames<-list.files(pattern = "*.txt",recursive = TRUE,full.names = TRUE)%>%as_tibble()
#These are the columns I would like:
colSelect=c("Date","Time","Timestamp" ,"PM2_5(ug/m3)","PM10(ug/m3)","PM01(ug/m3)","Temperature(C)", "Humidity(%RH)", "CO2(ppm)")
#This is how I read them if they have the same columns
ldf <- vroom::vroom(filenames, col_select = colSelect,delim=";",id = "sensor" )%>%janitor::clean_names()清洁头脚本
我已经写了一个破坏性的脚本,它将读取整个文件,清除空格的标题,删除该文件并重写(vroom抱怨有时无法用相同的名称打开X数千个文件)文件。不是一种高效的做事方式。
cleanHeaders<-function(filename){
d<-vroom::vroom(filename,delim=";")%>%janitor::clean_names()
#print(head(d))
if (file.exists(filename)) {
#Delete file if it exists
file.remove(filename)
}
vroom::vroom_write(d,filename,delim = ";")
}
lapply(filenames,cleanHeaders) 发布于 2021-04-01 15:16:02
fread的select参数允许整数索引。如果所需列始终位于相同位置,则您的工作就完成了。
colIndexes = c(1,3,4,7,9,18,21)
data = lapply(filenames, fread, select = colIndexes)我想advice也有这种功能,但是由于您已经在选择您想要的列,所以我认为懒洋洋地评估您的字符列不会有任何帮助,所以我建议您坚持使用data.table。
但是,对于更健壮的解决方案,由于您无法控制表的结构:您可以读取每个文件的一行,捕获和清除列名,然后将它们与干净版本的colSelect向量相匹配。
library(data.table)
library(janitor)
library(purrr)
filenames <- list.files(pattern = "*.txt",
recursive = TRUE,
full.names = TRUE)
# read the first row of data to capture and clean the column names
clean_col_names <- function(filename){
colnames(janitor::clean_names(fread(filename, nrow = 1)))
}
clean_column_names <- map(.x = filenames,
.f = clean_col_names)
# clean the colSelect vector
colSelect <- janitor::make_clean_names(c("Date",
"Time",
"Timestamp" ,
"PM2_5(ug/m3)",
"PM10(ug/m3)",
"PM01(ug/m3)",
"Temperature(C)",
"Humidity(%RH)",
"CO2(ppm)"))
# match each set of column names against the clean colSelect
select_indices <- map(.x = clean_column_names,
.f = function(cols) match(colSelect, cols))
# use map2 to read only the matched indexes for each column
data <- purrr::map2(.x = filenames,
.y = select_indices,
~fread(input = .x, select = .y))(在这里,purrr可以很容易地被传统的lapply替换,我选择purrr是因为它更干净的公式符号)
https://stackoverflow.com/questions/66905096
复制相似问题