Считайте несколько CSV в R в зависимости от того, где начинается заголовок, и скомпилируйте

Я удалил эту ошибку, записав следующий код

Open Terminal

  1. openssl req -newkey rsa: 2048 -new -nodes -keyout key.pem -out csr .pem
  2. openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt

Теперь используйте server.crt и key .pem file

файл app.js или server.js

var https = require('https');
var https_options = {
  key: fs.readFileSync('key.pem', 'utf8'),
  cert: fs.readFileSync('server.crt', 'utf8')
};

var server = https.createServer(https_options, app).listen(PORT);
console.log('HTTPS Server listening on %s:%s', HOST, PORT);

Он работает, но сертификат не доверен. Вы можете просмотреть изображение в файле изображения.

0
задан D Kincaid 16 January 2019 в 18:35
поделиться

3 ответа

Вот базовое решение R, которое помещает процесс поиска строки заголовка и последующего чтения файла в цикл для обработки каталога файлов.

    #define column names
    #columnnames<-c("agency_cd","site_no", "datetime", "tz_cd", "Gage height", "Discharge")

    #find files that match pattern
    fname<-dir( pattern = "file[0-9]\\.csv")

    #loop and read all files
    dfs<-lapply(fname, function(f) {
    #find header row
    headerline<-grep("agency_cd", readLines(f))
    #read data with header row and following row
    #by reading the header row bind will align the columns
    df<- read.csv(f, skip=headerline-1, stringsAsFactors = FALSE)
})

finalanswer<-do.call(rbind, dfs)

> finalanswer
#  agency_cd site_no     datetime tz_cd Gage.height Discharge
#        5s     15s          20d    6s         14n       14n
#      USGS 4294000 6/24/13 0:00   EDT        1.63      1310
#      USGS 4294000 6/24/13 0:15   EDT        1.59      1250
#        5s     15s          20d    6s         14n       14n
#      USGS 4294002 6/24/13 0:00   EDT        1.63      1310
#      USGS 4294002 6/24/13 0:15   EDT        1.59      1250

Теперь нужно удалить строки без USGS, а затем преобразовать столбцы из символьных в числовые.

Обратите внимание на "\". в функции dir точка имеет особое значение в регулярных выражениях. Точка означает любой символ. Чтобы точка означала просто точку, избегайте ее с двойным \ in R.

0
ответ дан Dave2e 16 January 2019 в 18:35
поделиться

Используя file1, показанный в вопросе, преобразуйте это в строки текста в Lines1, а затем прочитайте это, используя read.table, как показано, и аналогично для file2.

Lines1 <- capture.output(write.table(file1, stdout(), row.names = FALSE, quote = FALSE))
ix <- grep("agency", Lines1) # line number of header
DF1 <- read.table(text = Lines1[-c(seq_len(ix-1), ix+1)], header = TRUE)

дает:

> DF1
  agency_cd site_no datetime tz_cd Gage height Discharge
1      USGS 4294000  6/24/13  0:00  EDT   1.63      1310
2      USGS 4294000  6/24/13  0:15  EDT   1.59      1250

Обновлен

исправлено.

0
ответ дан G. Grothendieck 16 January 2019 в 18:35
поделиться

Я нашел 2 решения. Этот первый использует большинство решений @ Dave2e, но вместо того, чтобы использовать do.call(rbind, dfs), чтобы связать все dfs в одно, я использовал dplyr::bind_rows(). do.call(rbind, dfs) не работал, потому что мои столбцы заголовков иногда имели немного разные имена, что приводило к этой ошибке: Error in match.names(clabs, names(xi)) : names do not match previous names. dplyr::bind_rows() был более гибким с разными именами столбцов. Я также использую readr::read_csv вместо read.csv для личных предпочтений.

# First solution using most of @Dave2e's solution
library(tidyverse)

# Path to the data
data_path <- "Data/RACC_2012-2016/discharge"
# Get all CSV file names
file_names = dir(data_path, pattern = "*.csv", recursive = TRUE)

# Loop and read all files
dfs <- lapply(file.path(data_path, file_names), function(f) {
  # Find header row
  headerline <- grep("agency_cd", readLines(f))
  # Read data with header row and following row
  # by reading the header row bind will align the columns
  df <- read_csv(f, col_types = cols(.default = "c"), skip = headerline-1)
}) %>% 
  # Bind all into one data frame
  bind_rows() %>% 
  # Filters the row below the header row that doesn't contain data
  dplyr::filter(agency_cd != "5s") %>% 
  # Combine "Gage Height" and "Gage height" columns into one
  # First rename the columns to make them easier to call
  rename(Gage_height = "Gage Height", Gage_height2 = "Gage height") %>% 
  mutate(Gage_height = ifelse(is.na(Gage_height), Gage_height2, Gage_height)) %>% select(-Gage_height2)

Второе решение выполняет то же самое, что и решение 1, за исключением того, что оно также позволило мне добавить исходные имена файлов в виде столбца в конечном кадре данных. Вместо lapply, как указано выше, я использую purrr::map. И я также использую пакет fs для работы с путями к файлам.

# Second solution

library(tidverse)
library(fs)

# Path to the data
data_path <- "Data/RACC_2012-2016/discharge"

# Bind all files together to form one data frame
discharge <-
  # Find all file names ending in CSV in all subfolders
  fs::dir_ls(data_path, regexp = "*.csv", recursive = TRUE) %>% 
  # Create a dataframe holding the file names
  data_frame(filename = .) %>% 
  # Read in all CSV files into a new data frame, 
         # Create a new column with the filenames
  mutate(file_contents = map(filename, 
                             # Here we append path to the data before the file name & force all columns to be as character
                             # because the typecasting was causing problems
                             # We use skip = grep("agency_cd", readLines(.))-1)) to find header row
                             ~ read_csv(., col_types = cols(.default = "c"), skip = grep("agency_cd", readLines(.))-1))
        ) %>% 
  # Unpack the list-columns to make a useful data frame
  unnest() %>% 
  # Filters the row below the header row that doesn't contain data
  dplyr::filter(agency_cd != "5s") %>% 
  # Combine "Gage Height" and "Gage height" columns into one
  # First rename the columns to make them easier to call
  rename(Gage_height = "Gage Height", Gage_height2 = "Gage height") %>% 
  mutate(Gage_height = ifelse(is.na(Gage_height), Gage_height2, Gage_height)) %>% select(-Gage_height2)

Спасибо всем за помощь! Я также получил помощь от: https://serialmentor.com/blog/2016/6/13/reading-and-combining-many-tidy-data-files-in-R и Как импортировать несколько файлов .csv одновременно?

0
ответ дан D Kincaid 16 January 2019 в 18:35
поделиться
Другие вопросы по тегам:

Похожие вопросы: