r - rename.sf(.tbl, !!!syms) 错误 : internal error: can't find `agr` columns

标签 r dplyr shiny shinydashboard sf

我正在尝试使用 R 中的 shapefile 将坐标转换为经纬度,但我收到以下错误消息

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

这是我名为“dvc_read”的 shapefile 示例数据

structure(list(lat = c(40.61955, 40.61955, 40.6659, 40.6659, 
40.6659, 40.6659), long = c(-74.02346, -74.02346, -73.99604, 
-73.99604, -73.99604, -73.99604), End_Lat = c("0", "40.61955", 
"40.66912", "40.67653", "40.66912", "40.66912"), End_Lng = c("0", 
"-74.02346", "-73.99678", "-74.00127", "-73.99678", "-73.99678"
), Year = c("2019", "2020", "2019", "2018", "2020", "2020"), 
    Month = c("9", "8", "2", "5", "1", "1"), Day = c("15", "3", 
    "5", "18", "20", "29"), Date = c("2019-09-15", "2020-08-03", 
    "2019-02-05", "2018-05-18", "2020-01-20", "2020-01-29"), 
    accident.description = c("One lane blocked", "Right and center lane blocked", 
    "Right lane blocked", "Road closed", "Two lanes blocked", 
    "Right lane blocked"), Severity = c("3", "3", "2", "4", "3", 
    "2"), City = c("Brooklyn", "Brooklyn", "Brooklyn", "Brooklyn", 
    "Brooklyn", "Brooklyn"), 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(-73.99604, 
    40.6659), class = c("XY", "POINT", "sfg")), structure(c(-73.99604, 
    40.6659), class = c("XY", "POINT", "sfg")), structure(c(-73.99604, 
    40.6659), class = c("XY", "POINT", "sfg")), structure(c(-73.99604, 
    40.6659), class = c("XY", "POINT", "sfg"))), class = c("sfc_POINT", 
    "sfc"), precision = 0, bbox = structure(c(xmin = -74.02346, 
    ymin = 40.61955, xmax = -73.99604, ymax = 40.6659), 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 = 6:11, class = c("sf", 
"data.frame"), sf_column = "geometry", agr = structure(c(NA_integer_, 
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_, 
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
), .Names = c("lat", "long", "End_Lat", "End_Lng", "Year", "Month", 
"Day", "Date", NA, "Severity", "City"), .Label = c("constant", 
"aggregate", "identity"), class = "factor"))

这是我的代码:

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

如果我使用 CSV 格式,我会收到错误消息:

Error in UseMethod("st_transform") : 
  no applicable method for 'st_transform' applied to an object of class "data.frame"

我重新安装并更新了所有这些软件包,但问题仍然存在:

library(dplyr)  # tidy data manipulation
library(stringr)  # string manipulation
library(janitor)  # misc tidy data manipulation
library(lubridate)  # dealing with dates and times
library(forcats)  # deal with factors
library(sf)  # geography
library(lubridate) # ymd
library(tidyverse)

有关错误消息内容的任何建议或建议。 感谢您的宝贵时间和提前帮助

更新二:

我根据您的建议更改了代码,并且运行没有任何问题。但是,这是我尝试在 Shiny 上运行的程序的一部分,当我使用数据的 CSV 版本时,我可以成功运行服务器和 UI,但是当我使用我创建的 shapefile 对象时,我运行进入其他错误,我用谷歌搜索了错误,看起来它与 Rstuido 中的一些不同设置有关,当我运行 shapefile 数据的不同样本时,我看到 R studio 的行为不一致。 这是我在运行 Shiny 应用程序时收到的错误消息

runApp('ShinyApp.R')
Error in sample.int(length(x), size, replace, prob) : 
  invalid first argument

这是 Shiny 的更新代码以及 UI 和服务器。如果您能在您的机器上运行它们并与我分享您的输出和对我收到的错误消息的想法,我将不胜感激。

dvc_wrangle <- dvc_read %>% 
  st_transform(crs = 4326) %>% 
  rename_with(tolower, everything()) %>% 
  mutate(across(where(is.character), tolower)) %>%  
  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("5"), "unknown", severity),
    Accident.Description = if_else(accident.description == "Road closed", "Road_closed", accident.description),
    City = if_else(str_detect(city, "x"), "unknown", city), City = if_else(
      city %in% c(
        "Brooklyn", "Jamaica", "Merrick", "Roosevelt", "unclassified"
      ), "unknown", city
    ), Accident.Description = str_replace_all(accident.description, "_", " ")
  ) %>% mutate(across(c(Severity, Accident.Description, City), tools::toTitleCase))


###
# 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(longitude = X, latitude = Y)


# Save objects ------------------------------------------------------------
saveRDS(dvc, "/Users/data/dvc.RDS")
write.csv(dvc, "/Users/data/dvc.csv")
# 

**# # Read pre-prepared data
dvc <- readRDS("/Users/data/dvc.RDS")** # the dvc.RDS object I want to call in my Shiny App
# 
# # Month order for dropdown input
mo_order <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun",
              "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

这是使用我创建的 dvc.RDS 对象的 UI 和服务器植入

# Load packages -----------------------------------------------------------
# Load packages
library(shiny)  # interactive app framework
library(shinydashboard)  # layout
#library(icon)  # for icons
#install.packages("flexdashboard")
#install.packages("janitor")
# Data manipulation and cleaning
library(dplyr)  # tidy data manipulation
library(stringr)  # string manipulation
library(janitor)  # misc tidy data manipulation
library(lubridate)  # dealing with dates and times
library(forcats)  # deal with factors
library(sf)  # geography
library(flexdashboard)  # layout of the tool (pages, frames, etc)
library(crosstalk)  # for allowing htmlwidgets to interact with shared data
library(leaflet)  # interactive maps
library(DT)  # interactive tables
    # UI ----------------------------------------------------------------------
    
    
    ui <- dashboardPage(
      
      skin = "black",
      
      dashboardHeader(
        
        title = "Event-based Traffic Speed Prediction System",
        titleWidth = 450
      ),  # end dashboardHeader()
      
      dashboardSidebar(
        HTML("<br>"),
        box(
          title = "About",
          icon("info-circle", lib = "font-awesome"), HTML("<a href='https://www.rostrum.blog/2019/01/18/deer-collisions/'> System info</a>"), HTML("<br>"),
          width = 12,
          background = "blue",
          collapsible = TRUE, collapsed = TRUE
        ),
        
        box(
          title = "How to",
          width = 12,
          background = "blue",
          collapsible = TRUE, collapsed = TRUE,
          HTML("<ul>
          <li>Upload dataset Model menu to update the map and table</li>
          <li>The map and table are in separate tabs</li>
          <li>You can zoom and drag the map around</li>
          <li>Click a marker on the map for details</li>
          <li>You can download your selection with the 'Download' button</li></ul>")
        ),
        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 ------------------------------------------------------------------
    
    # Server ------------------------------------------------------------------
    
    
    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
    
    
    # Run ---------------------------------------------------------------------
    
    
 shinyApp(ui, server)

我通过删除 Tidyverse 软件包找到了一些建议,但这并没有解决我的问题。

如有任何建议或想法,我们将不胜感激。

最佳答案

我们可以使用 rename_with 代替 _all/_at,后者已被弃用,取而代之的是 across

library(dplyr)
library(lubridate)
library(sf)
library(stringr)
 dvc_read %>% 
  st_transform(crs = 4326) %>% rename_with(tolower, everything()) %>% mutate(across(where(is.character), tolower)) %>%  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"), "unknown", city), City = if_else(
      city %in% c(
        "Brooklyn", "Jamaica", "Merrick", "Roosevelt", "unclassified"
      ), "unknown", city
    ), Accident.Description = str_replace_all(accident.description, "_", " ")
  ) %>% mutate(across(c(Severity, Accident.Description, City), tools::toTitleCase))

-输出

Simple feature collection with 6 features and 16 fields
Geometry type: POINT
Dimension:     XY
Bounding box:  xmin: -74.02346 ymin: 40.61955 xmax: -73.99604 ymax: 40.6659
Geodetic CRS:  WGS 84
        lat      long  end_lat   end_lng year month day       date          accident.description severity     city
6  40.61955 -74.02346        0         0 2019     9  15 2019-09-15              one lane blocked        3 brooklyn
7  40.61955 -74.02346 40.61955 -74.02346 2020     8   3 2020-08-03 right and center lane blocked        3 brooklyn
8  40.66590 -73.99604 40.66912 -73.99678 2019     2   5 2019-02-05            right lane blocked        2 brooklyn
9  40.66590 -73.99604 40.67653 -74.00127 2018     5  18 2018-05-18                   road closed        4 brooklyn
10 40.66590 -73.99604 40.66912 -73.99678 2020     1  20 2020-01-20             two lanes blocked        3 brooklyn
11 40.66590 -73.99604 40.66912 -73.99678 2020     1  29 2020-01-29            right lane blocked        2 brooklyn
                     geometry       Date Month Severity          Accident.Description     City
6  POINT (-74.02346 40.61955) 2019-09-15   Sep  Unknown              One Lane Blocked Brooklyn
7  POINT (-74.02346 40.61955) 2020-08-03   Aug  Unknown Right and Center Lane Blocked Brooklyn
8   POINT (-73.99604 40.6659) 2019-02-05   Feb  Unknown            Right Lane Blocked Brooklyn
9   POINT (-73.99604 40.6659) 2018-05-18   May        4                   Road Closed Brooklyn
10  POINT (-73.99604 40.6659) 2020-01-20   Jan  Unknown             Two Lanes Blocked Brooklyn
11  POINT (-73.99604 40.6659) 2020-01-29   Jan  Unknown            Right Lane Blocked Brooklyn

关于r - rename.sf(.tbl, !!!syms) 错误 : internal error: can't find `agr` columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70852093/

相关文章:

R/dplyr : Using a loop to create lags and calculate cumulative sums based on column names

带有滚动条的 R Shiny 多选

r - Shiny 的应用程序中的图像输出

r - 如何将完整的数据框对象复制到剪贴板?

r - 绘制带孔的 "donut"多边形

r - 使用 R/Rcpp 在连续索引处切片字符串?

R:按重叠大小在维恩图中重叠颜色

r - 如何在 ggplot 中有效地按比例重新排序因子?

r - 在 vegan 函数中使用并行处理?

r - 在 R : script works, 中的移动日期窗口上缩放变量,但速度慢得令人无法接受。优化方法? rstats