使用read.csv清理数据

时间:2017-05-16 08:23:13

标签: r data-cleaning read.csv

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

我的(不是很友好的).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次我喜欢拥有的东西以及在哪里找到它。

在这两种情况下,由于.csv,括号等空间丢失,我甚至无法实现目标。我猜的同时问题太多了......

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

虽然您需要的最终形式将非常依赖于相关文件的详细信息,但是您在此处提供的内容可以在不过多精神错乱的情况下破解数据:

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
;;;"