0

遇到除以零错误

嗨,堆栈社区!我今天工作时遇到了这个错误。我不确定如何解决它。我读到在我的 mutate 中使用 na.rm,我试过了,但没有用。我可能完全错了。


library("DBI")
library("dbplyr")
library("odbc")
library("dplyr")
library("stringr")
library("tidyverse")
library("lubridate")


  select(CustomerID, PostalCodeID, OrderID, ItemID, WrittenSales, WrittenUnits, TransCodeID, SalesType, ProductID, ProductName, GroupID, SubGroupID, CategoryID, TransDate, LocationID, LocationName) %>%

  filter(SalesType == "W",
         LocationID %in% Louisville) %>%

  group_by(CustomerID, PostalCodeID, WrittenSales, TransCodeID, SalesType, ProductID, ProductName, GroupID, SubGroupID, CategoryID, TransDate, LocationID, LocationName) %>%
  summarise(WrittenUnits_purchased = sum(WrittenUnits)) %>%
  ungroup() %>%

  group_by(CustomerID) %>%
  mutate(prop_of_total = WrittenUnits_purchased/sum(WrittenUnits_purchased)) %>%
  ungroup()```
4

1 回答 1

1

虽然这是一个 SQL 问题,但它可以在您的代码中得到缓解。

设置:

# library(odbc) or similar, for the DB driver
# con <- DBI::dbConnect(...)
DBI::dbExecute(con, "create table r2 (x int, y int)")
# [1] 0
DBI::dbExecute(con, "insert into r2 (x,y) values (1,1),(2,0)")
# [1] 2
DBI::dbGetQuery(con, "select * from r2")
#   x y
# 1 1 1
# 2 2 0

基础 R 中的问题演示和基于 SQL 的修复:

DBI::dbGetQuery(con, "select x/y as xy from r2")
# Error in result_fetch(res@ptr, n) : 
#   nanodbc/nanodbc.cpp:2593: 22012: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Divide by zero error encountered. 
# Warning in dbClearResult(rs) : Result already cleared
DBI::dbGetQuery(con, "select (case when y = 0 then null else x/y end) as xy from r2")
#   xy
# 1  1
# 2 NA

由于您使用的是dbplyr,这就是事情的另一面:

library(dplyr)
library(dbplyr)
tbl(con, "r2") %>%
  collect()
# # A tibble: 2 x 2
#       x     y
#   <int> <int>
# 1     1     1
# 2     2     0
tbl(con, "r2") %>%
  mutate(xy = x/y) %>%
  collect()
# Error in result_fetch(res@ptr, n) : 
#   nanodbc/nanodbc.cpp:2593: 22012: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Divide by zero error encountered. 
# Warning in dbClearResult(res) : Result already cleared
tbl(con, "r2") %>%
  mutate(xy = if_else(y == 0, NA, x/y)) %>%
  collect()
# # A tibble: 2 x 3
#       x     y    xy
#   <int> <int> <int>
# 1     1     1     1
# 2     2     0    NA
于 2020-02-13T19:18:49.030 回答