【发布时间】:2021-12-01 18:40:04
【问题描述】:
我有一个tibble (data.frame),我需要对其应用许多类型更新。我有一个描述所需类型的 readr::col_spec 对象,但由于数据不是源自 csv 文件,因此我无法使用 read_csv(..., col_types=cspec) 将更改应用于指定列。
由于col_spec 是一种专门为指定所需数据类型而设计的数据结构,但我仍将其直接用作为我应用更改的函数的输入,而不是编写长的自定义脚本来应用不同的列。请参阅以下示例:
library(tidyverse)
# Subset starwars to get sw (comparable to my input data)
sw <- starwars %>%
select(name, height, ends_with("_color")) %>%
slice(c(1,4,5,19))
sw
#> # A tibble: 4 × 5
#> name height hair_color skin_color eye_color
#> <chr> <int> <chr> <chr> <chr>
#> 1 Luke Skywalker 172 blond fair blue
#> 2 Darth Vader 202 none white yellow
#> 3 Leia Organa 150 brown light brown
#> 4 Yoda 66 white green brown
# The col_spec that I have
cspec <- cols(
hair_color = col_factor(c("brown", "blond", "white", "none")),
skin_color = col_factor(c( "green", "light", "fair", "white")),
eye_color = col_factor(c("blue", "brown", "yellow"))
)
# I would like to apply the col_spec directly to sw
# A not so great workaround is to use a tempfile
tf <- tempfile()
sw %>% write_csv(tf)
sw_fct <- read_csv(tf, col_types=cspec)
# This is more or less the result I am after:
# But note how info on other columns (height) is lost in the roundtrip
sw_fct
#> # A tibble: 4 × 5
#> name height hair_color skin_color eye_color
#> <chr> <dbl> <fct> <fct> <fct>
#> 1 Luke Skywalker 172 blond fair blue
#> 2 Darth Vader 202 none white yellow
#> 3 Leia Organa 150 brown light brown
#> 4 Yoda 66 white green brown
【问题讨论】: