我在C:\ Deskop \ Test文件夹中有多个DBF文件。例如,我在下面列出了5个DBF文件名。
week_1_avg_199811_var86_TBL.dbf
week_1_avg_200510_var86_TBL.dbf
week_2_avg_200009_var86_TBL.dbf
week_2_avg_200309_var86_TBL.dbf
week_3_avg_200011_var86_TBL.dbf
每个文件有5列和1410行。例如,(week_1_avg_199811_var86_TBL.dbf)我将列出5行。每个DBF文件中的列1到4是相同的。
T_R ZONE COUNT AREA MEAN
T10S-R26W 1 1 0.0156 29.9412
T10S-R27W 1 1 0.0156 30.1242
T10S-R28W 1 1 0.0156 29.7399
T10S-R2E 1 1 0.0156 37.7858
T10S-R2W 1 1 0.0156 34.6999
我想输出一个读取上述(所有)DBF文件的CSV文件(Output.csv),如下所示。
Output.csv
YEAR T_R Sep_week_1 Oct_week_1 Nov_week_1
1998 T10S-R26W <some_value> <some_value> 29.9412
1998 T10S-R27W <some_value> <some_value> 30.1242
1998 T10S-R28W <some_value> <some_value> 29.7399
1998 T10S-R2E <some_value> <some_value> 37.7858
1998 T10S-R2W <some_value> <some_value> 34.6999
2005 T10S-R26W <some_value> <some_value> <some_value>
2005 T10S-R27W <some_value> <some_value> <some_value>
2005 T10S-R28W <some_value> <some_value> <some_value>
2005 T10S-R2E <some_value> <some_value> <some_value>
2005 T10S-R2W <some_value> <some_value> <some_value>
有人可以帮助我如何在R中实现这一目标?
我有以下代码读取文件夹中的所有.dbf文件,但我需要通过读取文件名来创建YEAR和每周值列。
rm(list=ls(all=TRUE))
setwd("C:/Deskop/Test")
graphics.off()
library("foreign")
library("purrr")
readDBA <- function(file){
df <- read.dbf(file, as.is=FALSE)
df$fileName <- file
return(df)
}
file.names <- list.files(pattern="*\\.dbf")
combinedData <- file.names %>% map_dfr(readDBA)
combinedData$Year <- gsub(".*_(\\d{4}).*", "\\1", combinedData$fileName)
combinedData$Month <- as.numeric(gsub(".*_\\d{4}(\\d{2}).*", "\\1", combinedData$fileName))
combinedData$Month_Abb <- month.abb[combinedData$Month]
combinedData$Week <- substr(combinedData$fileName, 6, 6)
cols <- c("Month_Abb","Week")
combinedData$Month_Week <- do.call(paste, c(combinedData[cols], sep="_wk"))
DT <- dcast(combinedData, Year + T_R + Month_Week + MEAN ~ Month_Week)
Using Month_Week as value column: use value.var to override.
感谢任何帮助,
提前致谢。
答案 0 :(得分:1)
这里的技巧是定义一个函数来读入.dba
文件,并添加一个文件名标签。然后,我们将使用purrr:map_dfr
来读取,然后在一个步骤中rbind()
每个文件。
require(purrr)
require(foreign)
readDBA <- function(file){
df <- read.dba(file, as.is=FALSE)
df$fileName <- file
return(df)
}
file.names <- list.files(pattern="*\\.dba")
combinedData <- file.names %>% map_dfr(readDBA)
然后有一点REGEX来获得年份和月份
combinedData$Year <- gsub(".*_(\\d{4}).*", "\\1", combinedData$fileName)
combinedData$Month <- gsub(".*_\\d{4}(\\d{2}).*", "\\1", combinedData$fileName)
我会让你弄清楚将周和月放在一起。
然后,您希望reshape2::dcast()
采用宽格式,类似这样的内容,但除非您提供数据框的实际样本,否则无法确定。
require(reshape2)
dcast(combinedData, Year + T_R ~ MonthWeek, value.var= "MEAN")
另外,R有一个方便的month.abb
向量,因此您可以使用month.abb[combinedData$Month]
获取月份缩写