如何 return 紧凑字符串表示中 R tibble 的 col 类型?

How to return the col type of a R tibble in compact string representation?

例如我有这样的小毛病。 测试 <- tibble(a = 10, b = "a")

有了这个输入,我想要一个可以 return "dc" 表示双精度和字符的函数。

我问这个的原因是我想读入很多文件。而且我不想让 read_table 函数来决定每列的类型。我可以手动指定字符串,但由于我要导入的实际数据有 50 列,因此手动操作非常困难。

谢谢。

虽然前面提到的 test %>% summarise_all(class) 会给你 class 列的名称,但它是以长格式给出的,而在这个问题中,你将它们转换为单字符代码,这意味着read_tablecol_types。要从 class 名称映射到单字母代码,您可以使用查找 table,这是一个(不完整的)示例 dput:

structure(list(col_type = c("character", "integer", "numeric", 
"double", "logical"), code = c("c", "i", "n", "d", "l")), .Names = c("col_type", 
"code"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-5L))

现在使用这个 table,我将其命名为 types,我们最终可以将列类型转换为单个字符串:

library(dplyr)
library(tidyr)
library(stringr)

test %>% 
  summarise_all(class) %>% 
  gather(col_name, col_type) %>% 
  left_join(types) %>% 
  summarise(col_types = str_c(code, collapse = "")) %>% 
  unlist(use.names = FALSE)

这会为每一列 (summarise_all) 获取 class,然后将它们收集到与列名称和列类型 (gather) 相匹配的 tibble 中。 left_join 匹配 col_type 列,并为每个列名称提供 1 个字符的短代码。现在我们不对列名做任何事情,所以只用 summarisestr_c 连接就可以了。最后 unlist 将字符串拉出 tibble。

test <- tibble(a = 10, b = "a")

test %>% purrr::map_chr(pillar::type_sum) %>% paste(collapse = "_")
# "dbl_chr"

参考资料: https://tibble.tidyverse.org/articles/types.html 当前 dplyr 版本:“1.0.9”。

谢谢大家的意见。我想更新答案以包含更多列类型并避免取代 dplyr 版本函数。

col_types readr 包中的参数比上面答案中提到的类型多一些:

types <-structure(list(code = c("c", "i", "d", "l", "f", "D", "T", "t"), 
                      col_type = c("chr", "int", "dbl", "lgl", "fct", "date", "dttm", "time")),
                 class = c("tbl_df", "tbl", "data.frame"), 
                 row.names = c(NA, -8L))

我删除了猜测和跳过选项。

使用 pillar::type_sum() 函数 returns 与 tibble 包中使用的相同的列缩写。所以

test |> 
    summarise(across(everything(), pillar::type_sum)) |> 
    pivot_longer(everything(), names_to = "col_names", values_to = "col_type") |> 
    left_join(types) |> 
    pull(code) |> 
    str_c(collapse = "")

这 returns 一个字符向量,可以在使用 readr 包时用作参数。这在读取和附加多个 csvs 时很有用,并且您想强制列类型以避免 bind_rows() 抛出错误。

因此 运行 map_dfr(all_csv_paths, read_csv) 不依赖于正确猜测列类型。