例如,我有一个这样的小标题。测试 <- tibble(a = 10, b = "a")
有了这个输入,我想要一个可以返回代表双精度和字符的“dc”的函数。
我问这个的原因是我想读很多文件。而且我不想让 read_table 函数来决定每列的类型。我可以手动指定字符串,但由于我要导入的实际数据有 50 列,因此手动执行非常困难。
谢谢。
虽然上述test %>% summarise_all(class)
内容将为您提供列的类名,但它以长格式提供,而在此问题中,您将它们转换为单个字符代码,这意味着read_table
col_types
. 要将类名映射到单字母代码,您可以使用查找表,这是一个(不完整)示例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))
现在使用这张表,我将其命名为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
),然后将它们收集到一个匹配列名称和列类型 ( gather
) 的 tibble 中。列上的left_join
匹配col_type
项并为每个列名提供简短的 1 字符代码。现在我们不对列名做任何事情,所以只需用 asummarise
和连接就可以了str_c
。最后unlist
把绳子从一个小标题中拉出来。
test <- tibble(a = 10, b = "a")
test %>% purrr::map_chr(pillar::type_sum) %>% paste(collapse = "_")
# "dbl_chr"