gpt4 book ai didi

运行 `rlang::last_error()`看看错误发生在哪里

转载 作者:行者123 更新时间:2023-12-02 18:21:48 24 4
gpt4 key购买 nike

我希望有人能帮助我解决我的代码的问题。我花了大约 5 个小时试图找出代码的问题,并检查了这些链接 1 , 2但无法找出我的代码的问题我正在尝试构建一个 Shiny 的应用程序,但是当我运行代码时,我不断收到错误消息:

Error: Problem with `mutate()` column `Date`.
ℹ `Date = ymd(Date)`.
x cannot coerce type 'closure' to vector of type 'character'

看起来问题在于创建日期和月份列,但我的数据中有它们,正如您在我的数据快照中看到的那样:

enter image description here

这是我用于读取数据和争论数据的代码

#Read and wrangle data 
dvc_read <- st_read("/Users/Desktop/shap/accident_data.shp", # shapefile stored in repo
stringsAsFactors = FALSE # read factor columns as character columns
)


dvc_wrangle <- dvc_read %>%
st_transform(crs = 4326) %>% # transform coords to latlong
# decapitalise everything for easy handling
rename_all(tolower) %>%
mutate_if(is.character, tolower) %>% # simplify strings
# deal with dates
mutate(
Date = ymd(Date), # the issue is with line
Month = case_when( # and this line
Month == 1 ~ "Jan", Month == 2 ~ "Feb",
Month == 3 ~ "Mar", Month == 4 ~ "Apr",
Month == 5 ~ "May", Month == 6 ~ "Jun",
Month == 7 ~ "Jul", Month == 8 ~ "Aug",
Month == 9 ~ "Sep", Month == 10 ~ "Oct",
Month == 11 ~ "Nov", Month == 12 ~ "Dec",
TRUE ~ "Unknown"
),
# clean up strings (not perfect)
Severity = if_else(Severity %in% c("1", "2", "3"), "unknown", Severity),
Accident.Description = if_else(Accident.Description == "Road closed", "Road_closed", Accident.Description),
City = if_else(str_detect(City, "x") == TRUE, "unknown", City),
City = if_else(
City %in% c(
"Brooklyn", "Jamaica", "Merrick", "Roosevelt", "unclassified",
), "unknown", City
),
# final name tidy-up
Accident.Description = str_replace_all(Accident.Description, "_", " ")
) %>%
# title case for these columns
mutate_at(vars(Severity, Accident.Description, City), tools::toTitleCase) # To Title Case


###
# extract latlong cols from sf geometry and bind back to df
dvc_xy <- as.data.frame(st_coordinates(dvc_wrangle))
dvc <- bind_cols(dvc_wrangle, dvc_xy) %>% rename(latitude = X, longitude = Y)
saveRDS(dvc,"/Users/Desktop/shap/dvc.RDS")
dvc <- readRDS("data/dvc.RDS")

# Month order for dropdown input
mo_order <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

为了更好地理解,我将添加 Ui 代码和服务器代码

用户界面代码:

ui <- dashboardPage(

dashboardHeader(

title = "Title",
titleWidth = 450
), # end dashboardHeader()

dashboardSidebar(
HTML("<br>"),

box(
title = "Filters",
width = 12,
background = "blue",
collapsible = TRUE, collapsed = FALSE,
selectInput(
inputId = "input_year",
label = "Year",
choices = sort(unique(dvc$Year)),
multiple = TRUE,
selected = sample(unique(dvc$Year), 1)
),
selectInput(
inputId = "input_month",
label = "Month",
choices = unique(dvc$Month[order(match(dvc$Month, mo_order))]),
multiple = TRUE,
selected = sample(unique(dvc$Month), 3)
),
selectInput(
inputId = "input_la",
label = "Accident.Description",
choices = sort(unique(dvc$Accident.Description)),
multiple = TRUE,
selected = sample(unique(dvc$Accident.Description), 3)
)
) # end box()
), # end dashboardSidebar()

dashboardBody(

fluidRow(
valueBoxOutput("output_valueselection"),
valueBoxOutput("output_valueyearla"),
valueBoxOutput("output_valueyear"),
tabBox(
id = "tabset1",
width = 12,
tabPanel("Map", leafletOutput("output_map", height = "600px")),
tabPanel("Table", dataTableOutput("output_table"))
)
) # end fluidRow()
) # end dashboardBody()

) # end of ui dashboardPage()

服务器代码:

server <- function(input, output) {

# Value box - year
output$output_valueyear <- renderValueBox({
shinydashboard::valueBox(
value = dvc %>% st_drop_geometry() %>% filter(Year %in% input$input_year) %>% count() %>% pull(),
subtitle = "Collisions in selected year(s)",
icon = icon("calendar", lib = "font-awesome"),
color = "blue",
width = 4
)
}) # end of renderValueBox

# Value box - year by la
output$output_valueyearla <- renderValueBox({
shinydashboard::valueBox(
value = dvc %>% st_drop_geometry() %>% filter(Year %in% input$input_year, Accident.Description %in% input$input_la) %>% count() %>% pull(),
subtitle = "Collisions in selected LA(s) and year(s)",
icon = icon("map-o", lib = "font-awesome"),
color = "blue",
width = 4
)
}) # end of renderValueBox

# Value box - total in your selection
output$output_valueselection <- renderValueBox({
shinydashboard::valueBox(
value = dvc %>% st_drop_geometry() %>% filter(Year %in% input$input_year, Month %in% input$input_month, Accident.Description %in% input$input_la) %>% count() %>% pull(),
subtitle = "Collisions in selection",
icon = icon("car", lib = "font-awesome"),
color = "blue",
width = 4
)
}) # end of renderValueBox

# Interactive map with Leaflet
output$output_map <- renderLeaflet({
dvc %>%
filter(
Year %in% input$input_year,
Month %in% input$input_month,
Accident.Description %in% input$input_la
) %>%
leaflet() %>%
addProviderTiles(providers$OpenStreetMap) %>%
addAwesomeMarkers(
icon = awesomeIcons(
icon = "exclamation-circle",
iconColor = "#FFFFFF",
library = "fa",
markerColor = "darkblue"
),
popup = ~paste0(
"<style>
td, th {
text-align: left;
padding: 3px;
}
</style>",
"<table>",
"<tr>","<td>", "Date", "</td>", "<td>", Date, "</td>", "<tr>",
"<tr>","<td>", "LA", "</td>", "<td>", Accident.Description, "</td>", "<tr>",
"<tr>","<td>", "City", "</td>", "<td>", City, "</td>", "<tr>",
"<tr>","<td>", "Species", "</td>", "<td>", Severity, "</td>", "<tr>",
"</table>"
)
)
}) # end of renderLeaflet

# Interactive table with DT
output$output_table <- renderDataTable({
dvc %>%
st_drop_geometry() %>%
filter(
Year %in% input$input_year,
Month %in% input$input_month,
Accident.Description %in% input$input_la
) %>%
select(
Date = Date,
Year = Year,
Month = Month,
`Accident.Description` = Accident.Description,
City = City,
`Severity` = Severity
) %>%
datatable(
filter = "top",
extensions = c("Scroller", "Buttons"), # scroll instead of paginate
rownames = FALSE, # remove row names
style = "bootstrap", # style
width = "100%", # full width
height = "800px",
options = list(
deferRender = TRUE,
# scroll
scrollY = 300,
scroller = TRUE,
# button
autoWidth = TRUE, # column width consistent when making selections
dom = "Blrtip",
buttons =
list(
list(
extend = "collection",
buttons = c("csv", "excel"), # download extension options
text = "Download" # text to display
)
)
) # end of options = list()
) # end of datatable()
}) # end of renderDataTable()

} # end of server function

非常感谢您帮助解决这个问题并修复我的代码中的错误。


更新:

这是我使用 dput() 的数据:

structure(list(lat = c(40.61955, 40.61955, 40.61955, 40.61955, 
40.61955, 40.61955), long = c(-74.02346, -74.02346, -74.02346,
-74.02346, -74.02346, -74.02346), Year = c("2020", "2020", "2019",
"2020", "2020", "2019"), Month = c("2", "11", "10", "9", "1",
"9"), Day = c("6", "21", "26", "20", "11", "15"), Date = c("2020-02-06",
"2020-11-21", "2019-10-26", "2020-09-20", "2020-01-11", "2019-09-15"
), Accident.Description = c("Right lane blocked", "Two lanes blocked",
"Two lanes blocked", "Right lane blocked", "Right lane blocked",
"One lane blocked"), Severity = c("3", "3", "3", "3", "3", "3"
), geometry = structure(list(structure(c(-74.02346, 40.61955), class = c("XY",
"POINT", "sfg")), structure(c(-74.02346, 40.61955), class = c("XY",
"POINT", "sfg")), structure(c(-74.02346, 40.61955), class = c("XY",
"POINT", "sfg")), structure(c(-74.02346, 40.61955), class = c("XY",
"POINT", "sfg")), structure(c(-74.02346, 40.61955), class = c("XY",
"POINT", "sfg")), structure(c(-74.02346, 40.61955), class = c("XY",
"POINT", "sfg"))), class = c("sfc_POINT", "sfc"), precision = 0, bbox = structure(c(xmin = -74.02346,
ymin = 40.61955, xmax = -74.02346, ymax = 40.61955), class = "bbox"), crs = structure(list(
input = "NAD83", wkt = "GEOGCRS[\"NAD83\",\n DATUM[\"North American Datum 1983\",\n ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n LENGTHUNIT[\"metre\",1]]],\n PRIMEM[\"Greenwich\",0,\n ANGLEUNIT[\"degree\",0.0174532925199433]],\n CS[ellipsoidal,2],\n AXIS[\"latitude\",north,\n ORDER[1],\n ANGLEUNIT[\"degree\",0.0174532925199433]],\n AXIS[\"longitude\",east,\n ORDER[2],\n ANGLEUNIT[\"degree\",0.0174532925199433]],\n ID[\"EPSG\",4269]]"), class = "crs"), n_empty = 0L)), row.names = c(NA,
6L), class = c("sf", "data.frame"), sf_column = "geometry", agr = structure(c(lat = NA_integer_,
long = NA_integer_, Year = NA_integer_, Month = NA_integer_,
Day = NA_integer_, Date = NA_integer_, Accident.Description = NA_integer_, Severity = NA_integer_), .Label = c("constant", "aggregate",
"identity"), class = "factor"))

更新二:

谢谢大家的帮助!我真的很感谢你给我的所有答案!我修复了代码问题,但我仍然面临一列“accident.description”列的问题。尽管我将名称更改为“意外”,但我认为该点导致了问题,但无法弄清楚。此列的错误消息如下:

Error: Problem with `mutate()` column `accident.description`.
ℹ `accident.description = if_else(...)`.
x object 'accident.description' not found

这是我更新的代码:

dvc_wrangle <- dvc_read %>% 
st_transform(crs = 4326) %>% # transform coords to latlong
# decapitalise everything for easy handling
rename_all(tolower) %>%
mutate_if(is.character, tolower) %>% # simplify strings
# deal with dates
mutate(
Date = ymd(date),
Month = case_when(
month == 1 ~ "Jan", month == 2 ~ "Feb",
month == 3 ~ "Mar", month == 4 ~ "Apr",
month == 5 ~ "May", month == 6 ~ "Jun",
month == 7 ~ "Jul", month == 8 ~ "Aug",
month == 9 ~ "Sep", month == 10 ~ "Oct",
month == 11 ~ "Nov", month == 12 ~ "Dec",
TRUE ~ "Unknown"
),
# clean up strings (not perfect)
Severity = if_else(severity %in% c("1", "2", "3"), "unknown", severity),
accident.description = if_else(accident.description == "Road closed", "Road_closed", accident.description),
City = if_else(str_detect(city, "x") == TRUE, "unknown", city),
City = if_else(
city %in% c(
"Brooklyn", "Jamaica", "Merrick", "Roosevelt", "unclassified",
), "unknown", city
),
# final name tidy-up
Accident.Description = str_replace_all(Accident.Description, "_", " ")
) %>%
# title case for these columns
mutate_at(vars(Severity, Accident.Description, City), tools::toTitleCase) # To Title Case

我将“道路封闭”更改为“道路封闭”,并将列名称更改为“事故”,如下所示,但仍然收到相同的错误消息:

   Accident = if_else(accident %in% c("Road closed", "Two lanes blocked", "One lane blocked"), "unknown", accident),

更新三:

感谢大家的帮助和支持!你们都太棒了!我根据您的注释和有关更新 II 的内容修复了代码,我将 LHS 上的“Accident.Description”列名称更改为大写而不是小写。但是,我收到一条新的错误消息:

Error in rename.sf(.tbl, !!!syms) : 
internal error: can't find `agr` columns

这是修改后的代码:

dvc_wrangle <- dvc_read %>% 
st_transform(crs = 4326) %>% # transform coords to latlong
# decapitalise everything for easy handling
rename_all(tolower) %>%
mutate_if(is.character, tolower) %>% # simplify strings
# deal with dates
mutate(
Date = ymd(date),
Month = case_when(
month == 1 ~ "Jan", month == 2 ~ "Feb",
month == 3 ~ "Mar", month == 4 ~ "Apr",
month == 5 ~ "May", month == 6 ~ "Jun",
month == 7 ~ "Jul", month == 8 ~ "Aug",
month == 9 ~ "Sep", month == 10 ~ "Oct",
month == 11 ~ "Nov", month == 12 ~ "Dec",
TRUE ~ "Unknown"
),
# clean up strings (not perfect)
Severity = if_else(severity %in% c("1", "2", "3"), "unknown", severity),
Accident.Description = if_else(accident.description == "Road closed", "Road_closed", accident.description),
City = if_else(str_detect(city, "x") == TRUE, "unknown", city),
City = if_else(
city %in% c(
"Brooklyn", "Jamaica", "Merrick", "Roosevelt", "unclassified",
), "unknown", city
),
# final name tidy-up
Accident.Description = str_replace_all(accident.description, "_", " ")
) %>%
# title case for these columns
mutate_at(vars(Severity, Accident.Description, City), tools::toTitleCase) # To Title Case

最佳答案

诊断

你的问题很简单。一旦Date列重命名为 date

  # decapitalise everything for easy handling
rename_all(tolower) %>%

然后是有问题的行

  # deal with dates
mutate(
Date = ymd(Date), # the issue is with line

包含表达式ymd(Date)引用不存在Date .

所以 R 在 data mask 之外搜索对于名为Date的东西...它找到的第一件事是函数 lubridate::Date() ,它(大概)已作为 Date 加载到您的工作区中,通过library(lubridate) 。请注意,函数也称为 "closures"在 R 中。

在那个有问题的表达中

ymd(Date)

因此,您将提供一个闭包作为 ymd() 的输入,其中 expects一个character向量。因此出现错误:

x cannot coerce type 'closure' to vector of type 'character'

解决方案

只需更改您的代码以引用 date列,现在为小写。

  # deal with dates
mutate(
Date = ymd(date),
# ^^^^

警告

据观察here通过 @bretauv ,您的代码稍后还会出现更多错误。有些您可以通过对其他列名称进行相同的更正来修复。

关于运行 `rlang::last_error()`看看错误发生在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70781242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com