根据现有数据框为{_csv创建一个col_types字符串规范

时间:2019-03-19 20:38:47

标签: r readr

我有一个data.frame或tibble,它们在一个脚本中写入了CSV文件。在另一个脚本中,相同的CSV文件被读取到data.frame或tibble中。使用read_csv()col_types=参数,我可以指定要读入的列类型。这是一个示例:

# Create an example dataframe
df <- tibble::tibble(a=1L
                     , b=1.0
                     , c="a"
                     , d=TRUE
                     , e=lubridate::ymd_hms("2019-03-19T13:15:18Z")
                     , f=lubridate::ymd("2019-03-19")
                     , g=factor("a"))

# Write csv to file
readr::write_csv(df, "temp.csv")

# read it back in, supplying a col_types string spec
readr::read_csv("temp.csv", col_types="idclTDf")
#> # A tibble: 1 x 7
#>       a     b c     d     e                   f          g    
#>   <int> <dbl> <chr> <lgl> <dttm>              <date>     <fct>
#> 1     1     1 a     TRUE  2019-03-19 13:15:18 2019-03-19 a

reprex package(v0.2.1)于2019-03-19创建

问题是我需要知道col_types=函数上的read_csv()参数(或者让我猜,这是我不想做的)。我想要一种获取原始df的方法,然后在将其写出之前,从col_types对象生成df字符串,该字符串可用于读取转储的CSV返回。也就是说,我想要一些东西可以在给定data.frame作为参数的情况下创建"idclTDf"字符串。

我看到这里有一个功能请求(我加了两美分):https://github.com/tidyverse/readr/issues/895

1 个答案:

答案 0 :(得分:3)

我确实有一个解决方案,它可以工作,但是我认为它很不完整,没有得到加强。这是我尝试的解决方法。

# https://github.com/tidyverse/readr/issues/895
# Create function to take a tibble and return a character string that can be used in `readr::read_csv()`
# as the `col_types` argument to re-read this back into a dataframe after it had been written out
# by `write_csv()`.

get_col_types_short <- function(.df) {
    # Get column classes from input dataframe
    lst_col_classes__ <- purrr::map(.df, ~ class(.x))

    # Map classes to known single-character col_types indicator
    vl_col_class_char__ <- purrr::map_chr(lst_col_classes__, function(.e) {
        dplyr::case_when(
              "logical" %in% .e   ~ "l"
            , "integer" %in% .e   ~ "i"
            , "numeric" %in% .e   ~ "d"
            , "double" %in% .e    ~ "d"
            , "character" %in% .e ~ "c"
            , "factor" %in% .e    ~ "f"
            , "Date" %in% .e      ~ "D"
            , "POSIXct" %in% .e   ~ "T"
            , TRUE                ~ "c"
        )
    })

    # Return vector of single-character col_type indicator.
    # Element name is the source column it came from.
    vl_col_class_char__
}

# Test it:
df <- tibble::tibble(a=1L
                     , b=1.0
                     , c="a"
                     , d=TRUE
                     , e=lubridate::ymd_hms("2019-03-19T13:15:18Z")
                     , f=lubridate::ymd("2019-03-19")
                     , g=factor("a"))

v__ <- get_col_types_short(df)

# Show what is actually returned
v__
#>   a   b   c   d   e   f   g 
#> "i" "d" "c" "l" "T" "D" "f"

# Collapse it to show how to use it
paste(v__, collapse="")
#> [1] "idclTDf"


# Write csv to file
readr::write_csv(df, "temp.csv")

# read it back in, using the above col_types string spec
readr::read_csv("temp.csv", col_types=paste(v__, collapse=""))
#> # A tibble: 1 x 7
#>       a     b c     d     e                   f          g    
#>   <int> <dbl> <chr> <lgl> <dttm>              <date>     <fct>
#> 1     1     1 a     TRUE  2019-03-19 13:15:18 2019-03-19 a

reprex package(v0.2.1)于2019-03-19创建