是否有dplyr
(或其他包)命令来获取SQL 表的列(字段?)类型?例如……
library(RSQLite)
library(dplyr)
data(iris)
dat_sql <- src_sqlite("test.sqlite", create = TRUE)
copy_to(dat_sql, iris, name = "iris_df")
iris_tbl <- tbl(dat_sql, "iris_df")
iris_tbl
# Source: query [?? x 5]
# Database: sqlite 3.8.6 [test.sqlite]
#
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# <dbl> <dbl> <dbl> <dbl> <chr>
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5.0 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
# 7 4.6 3.4 1.4 0.3 setosa
# 8 5.0 3.4 1.5 0.2 setosa
# 9 4.4 2.9 1.4 0.2 setosa
# 10 4.9 3.1 1.5 0.1 setosa
# # ... with more rows
我对一个命令很感兴趣,它会告诉我前四列的类型是 dbl
,最后一个是 chr
(或者更好的是,R类型 numeric
和 character
) 实际上 收集
内存中的数据。既然是印出来的,总得有办法吧?我尝试了 str
无济于事:
str(iris_tbl)
# List of 2
# $ src:List of 2
# ..$ con :Formal class 'SQLiteConnection' [package "RSQLite"] with 5 slots
# .. .. ..@ Id :<externalptr>
# .. .. ..@ dbname : chr "test.sqlite"
# .. .. ..@ loadable.extensions: logi TRUE
# .. .. ..@ flags : int 6
# .. .. ..@ vfs : chr ""
# ..$ path: chr "test.sqlite"
# ..- attr(*, "class")= chr [1:3] "src_sqlite" "src_sql" "src"
# $ ops:List of 3
# ..$ src :List of 2
# .. ..$ con :Formal class 'SQLiteConnection' [package "RSQLite"] with 5 slots
# .. .. .. ..@ Id :<externalptr>
# .. .. .. ..@ dbname : chr "test.sqlite"
# .. .. .. ..@ loadable.extensions: logi TRUE
# .. .. .. ..@ flags : int 6
# .. .. .. ..@ vfs : chr ""
# .. ..$ path: chr "test.sqlite"
# .. ..- attr(*, "class")= chr [1:3] "src_sqlite" "src_sql" "src"
# ..$ x :Classes 'ident', 'sql', 'character' chr "iris_df"
# ..$ vars: chr [1:5] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...
# ..- attr(*, "class")= chr [1:3] "op_base_remote" "op_base" "op"
# - attr(*, "class")= chr [1:4] "tbl_sqlite" "tbl_sql" "tbl_lazy" "tbl"
# NULL
最佳答案
打印远程表的预览时,dplyr 似乎确实在表的前几行使用了 collect
。因为 dplyr 会检索一些示例数据,所以您也可以这样做。
在这里,我们使用head
查询前几行,收集
查询结果,并检查每一列的类。
iris_tbl %>%
head %>%
collect %>%
lapply(class) %>%
unlist
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> "numeric" "numeric" "numeric" "numeric" "character"
(当与数据框一起使用时,lapply
会按列应用函数,因此它会将 class
应用于每一列。)
要获取 dplyr 使用的类型名称,请使用 type_sum
。
iris_tbl %>% head %>% collect %>% lapply(type_sum) %>% unlist
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> "dbl" "dbl" "dbl" "dbl" "chr"
关于r - 使用 dplyr 获取 SQL 表的列类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39357143/