Вы можете сделать это, используя readr::read_fwf()
, если можете указать начальную и конечную позиции каждого столбца:
library(readr)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
fname <- 'sample.txt'
write_file(
' Año Mes Día Hora Min SO2 NOx CO O3 PM10 PM2.5 VelV DirV Temp SO2_MH NOx_MH CO_MH O3_MH PM10_MH PM2.5_MH Pred_SO2 Pred_NOx PredBin_SO2 PredBin_NOx CodM_SO2 CodM_NOx Mensaje_SO2 Mensaje_NOx
2018 5 15 16 38 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 99.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 0 0
2018 5 15 16 39 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 99.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 0 0
2018 5 16 11 29 4.15 7.51 0.33 77.00 13.00 5.00 1.13 259.00 14.50 4.15 7.51 0.33 77.00 13.00 5.00 4.15 7.51 0.03 0.00 1 1 No hay alarma No hay alarma
2018 5 16 11 30 4.15 7.51 0.33 77.00 13.00 5.00 1.13 259.00 14.50 4.15 7.51 0.33 77.00 13.00 5.00 4.15 7.51 0.03 0.00 1 1 No hay alarma No hay alarma ',
fname
)
hdr <- read_lines(fname,n_max = 1)
cnames <- hdr %>%
trimws()%>%
strsplit('\\s+')%>%
unlist()
m <- gregexpr('\\S(?=\\s|$)',hdr,perl = T) # Find end position of columns
epos <-unlist(m)
spos <- lag(epos+1,1,default = 1)
read_fwf(fname,fwf_positions(start = spos,end = epos,col_names = cnames),skip = 1)
#> Parsed with column specification:
#> cols(
#> .default = col_double(),
#> Mensaje_SO2 = col_character(),
#> Mensaje_NOx = col_character()
#> )
#> See spec(...) for full column specifications.
#> # A tibble: 4 x 28
#> Año Mes Día Hora Min SO2 NOx CO O3 PM10 PM2.5 VelV
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 2018 5 15 16 38 -1 -1 -1 -1 -1 -1 -1
#> 2 2018 5 15 16 39 -1 -1 -1 -1 -1 -1 -1
#> 3 2018 5 16 11 29 4.15 7.51 0.33 77 13 5 1.13
#> 4 2018 5 16 11 30 4.15 7.51 0.33 77 13 5 1.13
#> # … with 16 more variables: DirV <dbl>, Temp <dbl>, SO2_MH <dbl>,
#> # NOx_MH <dbl>, CO_MH <dbl>, O3_MH <dbl>, PM10_MH <dbl>, PM2.5_MH <dbl>,
#> # Pred_SO2 <dbl>, Pred_NOx <dbl>, PredBin_SO2 <dbl>, PredBin_NOx <dbl>,
#> # CodM_SO2 <dbl>, CodM_NOx <dbl>, Mensaje_SO2 <chr>, Mensaje_NOx <chr>
Создано в 2019-05-21 с помощью пакета Представление (v0.3.0)
Я получаю 28 столбцов с ожидаемыми значениями