我需要将许多文件读入R中,进行一些清理,然后将它们组合成一个数据帧。这些文件基本上都是这样开始的:
=~=~=~=~=~=~=~=~=~=~=~= PuTTY log 2016.07.11 09:47:35 =~=~=~=~=~=~=~=~=~=~=~=
up
Upload #18
Reader: S1 Site: AA
--------- upload 18 start ---------
Type,Date,Time,Duration,Type,Tag ID,Ant,Count,Gap
E,2016-07-05,11:45:44.17,"upload 17 complete"
D,2016-07-05,11:46:24.69,00:00:00.87,HA,900_226000745055,A2,8,1102
D,2016-07-05,11:46:43.23,00:00:01.12,HA,900_226000745055,A2,10,143
列标题为"Type,Date,Time,Duration,Type,Tag ID,Ant,Count,Gap"
的行。数据应该有9列。问题是标题字符串上方的行数对于每个文件都是不同的,所以我不能简单地使用skip = 5.我也只需要以"D,"
开头的行,其他一切都是消息,而不是数据。
读取我的文件的最佳方法是什么,确保我有9列并跳过所有垃圾?
我一直在使用read_csv
包中的readr()
函数,因为到目前为止它产生的格式问题最少。但是,我对任何新想法持开放态度,包括以"D,"
开头的方式阅读。我玩弄了read.table
和skip = grep("Type," readLines(i))
,但它似乎没有正确找到标题字符串。这是我的基本代码:
dataFiles <- Sys.glob("*.*")
datalist <- list()
for (i in dataFiles) {
d01 <- read_csv(i, col_names = F, na = "NA", skip = 35)
# do clean-up stuff
datalist[[i]] <- d
}
答案 0 :(得分:1)
如果标题行始终以单词Type
开头,则可以从初始读取中省略skip
选项,然后删除标题行之前的所有行。这里有一些代码可以帮助您入门(未经测试):
dataFiles <- Sys.glob("*.*")
datalist <- list()
for (i in dataFiles) {
d01 <- read_csv(i, col_names = F, na = "NA")
headerRow <- which( d01[,1] == 'Type' )
d01 <- d01[headerRow+1,] # This keeps all rows after the header row.
# do clean-up stuff
datalist[[i]] <- d
}
如果您想保留标题,可以使用:
for (i in dataFiles) {
d01 <- read_csv(i, col_names = F, na = "NA")
headerRow <- which( d01[,1] == 'Type' )
d01 <- d01[headerRow+1,] # This keeps all rows after the header row.
header <- d01[headerRow,] # Get names from header row.
setNames( d01, header ) # Assign names.
# do clean-up stuff
datalist[[i]] <- d
}
答案 1 :(得分:1)
您可以使用自定义函数循环遍历每个文件,并仅过滤D
列中以type
开头的文件,并在最后将它们全部绑定在一起。如果您希望将它们作为单独的列表,请删除bind_rows
。
load_data <-function(path) {
require(dplyr)
setwd(path)
files <- dir()
read_files <- function(x) {
data_file <- read.csv(paste(path, "/", x, ".csv", sep = ""), stringsAsFactors = FALSE, na.strings=c("","NA"))
row.number <- grep("^Type$", data_file[,1])
colnames(data_file) <- data_file[row.number,]
data_file <- data_file[-c(1:row.number+1),]
data_file <- data_file %>%
filter(grepl("^D", Type))
return(data_file)
}
data <- lapply(files, read_files)
}
list_of_file <- bind_rows(load_data("YOUR_FOLDER_PATH"))
答案 2 :(得分:1)
另一个基本的R解决方案如下:您按行读取文件,获取行的索引,以&#34; D&#34;和标题行。之后,您只需将这些行拆分为&#34;,&#34;并将其放在data.frame中,并将标题行中的名称分配给它。
lines <- readLines(i)
dataRows <- grep("^D,", lines)
names <- unlist(strsplit(lines[grep("Type,", lines)], split = ","))
data <- as.data.frame(matrix(unlist(strsplit(lines[dataRows], ",")), nrow = length(dataRows), byrow=T))
names(data) <- names
输出:
Type Date Time Duration Type Tag ID Ant Count Gap
1 D 2016-07-05 11:46:24.69 00:00:00.87 HA 900_226000745055 A2 8 1102
2 D 2016-07-05 11:46:43.23 00:00:01.12 HA 900_226000745055 A2 10 143