正则表达式和文件处理

Regex and file processing

这个问题与 R 有关,但实际上并不是特定于语言本身。我有一堆具有这种通用格式 "sitename_03082015.csv" 的 csv 文件。这些文件有 5 列和不同的行

Host    MaximumIn   MaximumOut  AverageIn   AverageOut
device1 30.63 Kbps  0 bps       24.60 Kbps  0 bps
device2 1.13 Mbps   24.89 Kbps  21.76 Kbps  461 bps
device5 698.44 Kbps 37.71 Kbps  17.49 Kbps  3.37 Kbps

我最终想读入所有文件并合并我能做的但是在合并期间我想读取站点名称和日期并将其添加到每个相关行所以输出看起来像这样

Host      MaximumIn     MaximumOut  AverageIn   AverageOut  Site Name   Date
device1   30.63 Kbps    0 bps       24.60 Kbps  0 bps       SiteA       3/7/15
device12  1.13 Mbps     24.89 Kbps  21.76 Kbps  461 bps     SiteA       3/8/15
device1   698.44 Kbps   37.71 Kbps  17.49 Kbps  3.37 Kbps   SiteB       3/7/15
device2   39.08 Kbps    1.14 Mbps   10.88 Kbps  27.06 Kbps  SiteB       3/8/15
device3   123.43 Kbps   176.86 Kbps 8.62 Kbps   3.78 Kbps   SiteB       3/9/15

使用我的 R 代码,我可以执行以下操作:

#Get list of file names
filenames<- list.files(pattern = ".csv$")

#This extracts everything up to the underscore to get site name
siteName <- str_extract(string = filenames, "[^_]*")

# Extract date from file names use
date <- str_extract(string = filenames, "\d{8}" )

使用下面的 R 代码,我可以合并所有文件,但不会添加我想要的站点名称和日期列。

myDF<-do.call("rbind", lapply(filenames, read.table, header=TRUE, sep=","))

我只是想不通如何提取站点和日期,添加和填充列以创建我理想的数据框,即上面的第二个 table。

最适合我的解决方案发布在下面:)

我立即想到的方法是在阅读带有附加信息的信息时执行cbind,然后再执行rbind。类似于此:

 myDF<-do.call("rbind", 
          lapply(filenames, 
                 function(x) cbind(read.table(x, header=TRUE, sep=","), 
                                              "Site Name" = str_extract(string = x, "[^_]*"),
                                              "Date" = as.Date(str_extract(string = x, "\d{8}"), "%m%d%Y"))))

我做过类似的东西,可以在这里应用。您可以添加更多以逗号分隔的文件名。也可以类似地提取站点。如果您需要更多帮助,请告诉我。

    ##Assuming your csv files are saved in location C:/"
    library(stringr)

    ##List all filenames
    fileNames <- c("hist_03082015.csv","hist_03092015.csv")

    ##Create a empty dataframe to save all output to
    final_df <- NULL

    for (i in fileNames) {
    ##Read CSV
    df <- read.csv(paste("C:/",i,sep=""),header = TRUE,
                 sep = ",",colClasses='character')
    ##Extract date from filename into a column
    df$Date <- gsub("\D","",i)
    ##Convert string to date
    df$Date <-as.Date(paste(str_sub(df$Date, 1, 2),
              str_sub(df$Date,  3,-5),
              str_sub(df$Date, 5,-1),sep="-"),"%d-%m-%Y")
    ##save all data into 1 dataframe 
    final_df <- rbind(final_df,df)
    print(summary(final_df))
    }