使用 read.csv 进行数据清理

data cleaning with read.csv

作为初学者,我想问一下,哪种方法更elegant/effective清理大.csv数据:我试过两种解决方案(找到help(),这里和文献中)但我不确定是否有更好的东西(即循环?)你可以建议我。

我的(R 不太友好).csv 数据(523 行,47 列,这里只是开头):

;;;
;;;
;;;
Name;#1;#2;#3
Correction;;;          
Date;19.09.2016;19.09.2016;19.09.2016
Time;12:05:03;12:06:01;12:07:00
T_int [ms];806;800;884
Ev [lx];1,31E+03;1,35E+03;1,27E+03
Ee [W/sqm] (380-780nm);4,22E+00;4,38E+00;4,17E+00
;;;
;;;
Chrom. Coord.;;;           
x;0,3657;0,3642;0,3643
y;0,3842;0,3831;0,3833
u';0,2126;0,2121;0,2121
v';0,5026;0,502;0,5021
;;;

我有兴趣只选择一些信息(523 行中的大约 450 行)并在最后有一个转置数据框,如:

   Date       Time     Ev   # ...
V2 2016-09-19 12:05:03 1310 # ...
V3 2016-09-19 12:06:01 1350 # ...
V4 2016-09-19 12:07:00 1270 # ...
# [...]

我试过的方法是:

Date <- t(read.csv2("filename", nrows=1, skip=5, header=F)[,-1])
Time <- t(read.csv2("filename", nrows=1, skip=6, header=F)[,-1])
Ev <- t(read.csv2("filename", nrows=1, skip=8, header=F)[,-1])
# [...] (for all the about 450 choosen vectors!!!)
df <- data.frame(Date = Date, Time = Time, Ev = Ev) # ...

columns <- c(n1, n2, n3, n4, n5, Date, Time, n6, Ev) # [...]
raw_csv <- t(read.csv2("filename", header=F, col.names = columns, colClasses = c(rep("NULL",5),rep("Date",2),"NULL","numeric")) # ...
df <- data.frame(raw_csv)

我觉得我找不到结构更好的东西,避免即分别定义 450 次我想要的东西以及在哪里找到它。

在这两种情况下,我什至没有到达我的 objective,因为 .csv 中丢失了空格、括号等。同时问题太多,我猜...

非常感谢您的帮助!

虽然您需要的最终形式将在很大程度上取决于相关文件的细节,但对于您在此处展示的内容,您可以毫不费力地破解数据:

library(tidyverse)

df <- read_csv2(file, col_names = FALSE) %>% 
    filter(rowSums(!is.na(.)) > 0) %>% 
    magrittr::set_rownames(.[[1]]) %>% 
    select(-1) %>% 
    t() %>% 
    as_data_frame() %>% 
    type_convert(col_types = cols(Date = col_date('%d.%m.%Y')), 
                 locale = locale(decimal_mark = ','))

df
#> # A tibble: 3 x 12
#>    Name Correction       Date     Time `T_int [ms]` `Ev [lx]`
#>   <chr>      <chr>     <date>   <time>        <int>     <dbl>
#> 1    #1       <NA> 2016-09-19 12:05:03          806      1310
#> 2    #2       <NA> 2016-09-19 12:06:01          800      1350
#> 3    #3       <NA> 2016-09-19 12:07:00          884      1270
#> # ... with 6 more variables: `Ee [W/sqm] (380-780nm)` <dbl>, `Chrom.
#> #   Coord.` <chr>, x <dbl>, y <dbl>, `u'` <dbl>, `v'` <dbl>

数据

file <- ";;;
;;;
;;;
Name;#1;#2;#3
Correction;;;          
Date;19.09.2016;19.09.2016;19.09.2016
Time;12:05:03;12:06:01;12:07:00
T_int [ms];806;800;884
Ev [lx];1,31E+03;1,35E+03;1,27E+03
Ee [W/sqm] (380-780nm);4,22E+00;4,38E+00;4,17E+00
;;;
;;;
Chrom. Coord.;;;           
x;0,3657;0,3642;0,3643
y;0,3842;0,3831;0,3833
u';0,2126;0,2121;0,2121
v';0,5026;0,502;0,5021
;;;"