从MySQL表加载数据时,通常会出现以下警告:
unrecognized MySQL field type 7 in column 26 imported as character
Unsigned INTEGER in col 3 imported as numeric如何正确地将数据库表加载到dataframe中,以便不显示这些警告?
我看到函数RMySQL::dbDataType()可以“确定S对象的SQL”。有没有办法告诉它哪种MySQL数据类型匹配数据帧中的哪种向量类型?
发布于 2016-01-29 15:15:35
您没有做错任何事情--RMySQL“有益”地给出了所有这些警告,以防万一这不是您想要的(几乎总是如此)。@hadley建议安装开发版本(0.11.x),据报道该版本解决了这一问题。否则,可以使用suppressWarnings(...),其中...是要隐藏警告的语句。或者接受它直到0.11版点击CRAN。
发布于 2019-02-25 22:59:56
从RMySQL切换到RMariaDB也会删除警告,参见https://github.com/r-dbi/RMySQL/issues/37。
发布于 2022-11-18 00:59:37
最好的选择可能是RMariaDB,但是如果您坚持使用RMySQL,可以忽略下面的函数(adapted from this answer)中的特定警告。
#' Suppress warnings matching regex
#'
#' @param expr Expression to evaluate
#' @param regex Regex pattern passed to grepl
#' @param ... Additional arguments passed to grepl
#'
#' @export
suppress_warnings_matching <- function(expr, pattern, ...) {
eval.parent(substitute(
withCallingHandlers(expr, warning = function(w) {
msg <- conditionMessage(w)
if (grepl(pattern, msg, ...)) {
invokeRestart("muffleWarning")
}
})
))
}我主要使用dbplyr与我的DB交互,这意味着当我在控制台中交互地执行collect或print时,查询实际上会被执行。如果使用pool,则在调用tbl时也会出现警告,因为由于某种原因,tbl.Pool中有字段查找。
以下内容应该有效,但并不完美。
# Override dplyr's collect with a more silent version
collect <- function(...) {
annoying_mysql_warning <- "Unsigned INTEGER in col [0-9]+ imported as numeric"
suppress_warnings_matching(dplyr::collect(...), annoying_mysql_warning)
}
# Override base print with a more silent version
print <- function(...) {
annoying_mysql_warning <- "Unsigned INTEGER in col [0-9]+ imported as numeric"
suppress_warnings_matching(base::print(...), annoying_mysql_warning)
}它在Rstudio控制台中打印时不起作用,而且我也不特别喜欢覆盖泛型函数。
在收集、交互式使用/打印以及有时在分配(当使用pool时)的警告中,一种更有效的方法是以下方法,这在我的所有用例中都有效:
# Suppress the warning on collect
.S3method("collect", "tbl_sql", function(...) {
annoying_mysql_warning <- "Unsigned INTEGER in col [0-9]+ imported as numeric"
suppress_warnings_matching(dbplyr:::collect.tbl_sql(...), annoying_mysql_warning)
})
# Suppress the warning on print (e.g. interactive use)
.S3method("print", "tbl_sql", function(...) {
annoying_mysql_warning <- "Unsigned INTEGER in col [0-9]+ imported as numeric"
suppress_warnings_matching(dbplyr:::print.tbl_sql(...), annoying_mysql_warning)
})
# Suppress the warning on `tbl`
.S3method("tbl", "DBIConnection", function(...) {
annoying_mysql_warning <- "Unsigned INTEGER in col [0-9]+ imported as numeric"
suppress_warnings_matching(dplyr:::tbl.DBIConnection(...), annoying_mysql_warning)
})
# Suppress the warning on `tbl` for pools
.S3method("tbl", "Pool", function(...) {
annoying_mysql_warning <- "Unsigned INTEGER in col [0-9]+ imported as numeric"
suppress_warnings_matching(pool:::tbl.Pool(...), annoying_mysql_warning)
})
})这个很好用!这并不理想,因为我们必须使用内部包函数(使用三冒号:::),但这对我来说是值得的!
避免在prod中使用这一点,但是,如果您这样做了,请确保您的dbplyr版本是冻结的,以避免坏的惊喜。
https://stackoverflow.com/questions/34399043
复制相似问题