在 readODS::read_ods 中指定 col_types

Specify col_types in readODS::read_ods

我想在 R 中读取一个 ods 文件的范围,其中第一列必须是字符,其他 40 列必须是双精度。如何指定 col_types? col_types = paste0("c", paste(rep("d", times = 40), collapse = "")) 不起作用,我收到错误 Unknown col_types. Can either be a class col_spec, NULL or NA。我找不到任何例子。有人提示解决方案吗?谢谢!

col_types 应该是 class col_spec。这意味着,您可以使用 readr::cols().

定义列类型

假设您在 table.ods 中有这个 table:

           A       B            C
1 characters numbers againnumbers
2          a       1            5
3          a       2            6
4          a       3            7
5          a       4            8

然后你可以指定列 readr::cols(): the first column (named characters here) as characters by readr::col_character() and others by default as numbers with readr::col_double():

library(readODS)
library(readr)

df <- read_ods("table.ods",
               col_types = cols(
                   characters = col_character(),
                   .default = col_double())
)

str(df)
#> 'data.frame':    4 obs. of  3 variables:
#> $ characters  : chr  "0" "1" "2" "3"
#> $ numbers     : num  1 2 3 4
#> $ againnumbers: num  5 6 7 8

(如果你想使用简单的方法,例如 "cdd",你需要将该字符串转换为 col_specreadr::as.col_spec(),但是它没有命名并且似乎没有read_ods().)

可以正常工作