AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-9198260

firmo23's questions

Martin Hope
firmo23
Asked: 2025-04-05 01:23:26 +0800 CST

Erro ao tentar filtrar meu conjunto de dados com base em um vetor de strings

  • 5

Como você pode ver no meu aplicativo abaixo, eu faço a filtragem, mas recebo Aviso: Erro na ordem: o argumento 1 não é um vetor ao tentar filtrar meus dados com o widget.

library(shiny)
library(shinydashboard)
library(dplyr)
library(plotly)
library(DT)
library(zoo)
library(shinyWidgets)

# Sample data
sample_data <- tibble::tibble(
  keyword = c("closing costs", "competitive commission", "curb appeal", "expert negotiation", 
              "home inspection", "market analysis", "mortgage pre-approval", "open house", 
              "price reduction", "staging tips"),
  gmb_id = rep("43763", 10),
  date = seq.Date(from = as.Date("2025-03-10"), by = "1 day", length.out = 10),
  pin_count = rep(39, 10),
  gmb_return = runif(10, -0.05, 0.05),
  gmb_abs_return = abs(runif(10, -0.05, 0.05))
)

ui <- dashboardPage(
  dashboardHeader(title = "🔧 Toy Pin Volatility"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Pin Volatility per Keyword", tabName = "pin_tab", icon = icon("map-pin")),
      pickerInput(
        inputId = "selected_keywords_pins",
        label = "Select Keyword(s)",
        choices = unique(sample_data$keyword),
        selected = unique(sample_data$keyword)[1:3],
        multiple = TRUE,
        options = list(`actions-box` = TRUE)
      )
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(
        tabName = "pin_tab",
        
        fluidRow(
          box(width = 12, DTOutput("volatility_table_pins"))
        )
      )
    )
  )
)

server <- function(input, output, session) {
  rolling_pins <- reactive({
    req(input$selected_keywords_pins)
    
    sample_data %>%
      filter(trimws(keyword) %in% trimws(input$selected_keywords_pins)) %>%
      arrange(keyword, gmb_id, date) %>%
      group_by(keyword, gmb_id) %>%
      mutate(
        rolling_volatility = zoo::rollapply(gmb_abs_return,
                                            width = 3,
                                            FUN = sd,
                                            fill = NA,
                                            align = "right")
      ) %>%
      ungroup() %>%
      na.omit()
  })
  
  
  output$volatility_table_pins <- renderDT({
    datatable(
      rolling_pins(),
      options = list(pageLength = 10, scrollX = TRUE),
      rownames = FALSE
    )
  })
}

shinyApp(ui, server)
  • 1 respostas
  • 47 Views
Martin Hope
firmo23
Asked: 2024-10-08 21:25:18 +0800 CST

Como usar eventReactive com valores padrão ao iniciar o aplicativo?

  • 5

Neste shinyaplicativo, quero exibir a tabela com minhas escolhas padrão depois que o aplicativo for iniciado pela primeira vez e, então, mudar somente depois de clicar, actionButton()como acontece agora.

library(shiny)
library(ggplot2)
library(dplyr)
library(glue)
library(reactable)
final_2023_with_percentile <- structure(list(player_name = c("Abbott, Andrew", "Abbott, Andrew", 
                                                             "Abbott, Andrew", "Abbott, Andrew", "Abreu, Bryan"), api_pitch_type = c("CH", 
                                                                                                                                     "CU", "FF", "ST", "FF"), `Horizontal Break` = c(14.5784810126582, 
                                                                                                                                                                                     -8.75646017699115, 7.72310797174571, -11.787027027027, -7.55102362204724
                                                                                                                                     ), `Induced Vertical Break` = c(10.763164556962, -3.3975221238938, 
                                                                                                                                                                     16.3276286579213, 5.79423423423423, 16.278188976378), `Pitch Velocity` = c(86.6278481012658, 
                                                                                                                                                                                                                                                80.8719764011799, 92.7466195761857, 82.9141141141141, 97.5663385826772
                                                                                                                                                                     ), pitch_usage = c(15.959595959596, 17.1212121212121, 50.050505050505, 
                                                                                                                                                                                        16.8181818181818, 41.1336032388664), avg_arm_angle = c(44.6095238095238, 
                                                                                                                                                                                                                                               49.552380952381, 45.7190476190476, 43.8, 40.1347222222222), pitch_group = c("Offspeed", 
                                                                                                                                                                                                                                                                                                                           "Breaking", "Fastball", "Breaking", "Fastball"), year = c(2023, 
                                                                                                                                                                                                                                                                                                                                                                                     2023, 2023, 2023, 2023), expected_arm_angle = c(45.3313248212314, 
                                                                                                                                                                                                                                                                                                                                                                                                                                     48.0091346481901, 43.3291879571372, 45.1739731517787, 42.3795663314202
                                                                                                                                                                                                                                                                                                                                                                                     ), difference = c(-0.721801011707591, 1.54324630419084, 2.38985966191041, 
                                                                                                                                                                                                                                                                                                                                                                                                       -1.3739731517787, -2.24484410919793), difference_percentile = c(11, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                       36, 61, 32, 59)), row.names = c(NA, -5L), class = c("tbl_df", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           "tbl", "data.frame"))
final_2024_with_percentile <- structure(list(player_name = c("Abbott, Andrew", "Abbott, Andrew", 
                                                             "Abbott, Andrew", "Abbott, Andrew", "Abreu, Bryan"), api_pitch_type = c("CH", 
                                                                                                                                     "CU", "FF", "ST", "FF"), `Horizontal Break` = c(14.8485, -8.75612903225807, 
                                                                                                                                                                                     8.8715142198309, -12.5934841628959, -6.10478571428571), `Induced Vertical Break` = c(12.4713, 
                                                                                                                                                                                                                                                                          -4.08215053763441, 16.2903920061491, 4.45031674208145, 16.6883571428571
                                                                                                                                                                                     ), `Pitch Velocity` = c(84.73375, 80.7849462365591, 92.7887009992314, 
                                                                                                                                                                                                             82.9180995475113, 96.6285714285714), pitch_usage = c(16.4812525751957, 
                                                                                                                                                                                                                                                                  11.495673671199, 53.6052740008241, 18.2117840955913, 46.6666666666667
                                                                                                                                                                                                             ), avg_arm_angle = c(43.508, 48.376, 44.82, 44.376, 43.0328947368421
                                                                                                                                                                                                             ), pitch_group = c("Offspeed", "Breaking", "Fastball", "Breaking", 
                                                                                                                                                                                                                                "Fastball"), year = c(2024, 2024, 2024, 2024, 2024), expected_arm_angle = c(45.5588206160552, 
                                                                                                                                                                                                                                                                                                            49.1467520143948, 43.9438816766548, 46.2666308980996, 41.945208160932
                                                                                                                                                                                                                                ), difference = c(-2.0508206160552, -0.770752014394823, 0.876118323345224, 
                                                                                                                                                                                                                                                  -1.8906308980996, 1.08768657591006), difference_percentile = c(44, 
                                                                                                                                                                                                                                                                                                                 19, 24, 43, 30)), row.names = c(NA, -5L), class = c("tbl_df", 
                                                                                                                                                                                                                                                                                                                                                                     "tbl", "data.frame"))


# UI
ui <- fluidPage(
  titlePanel("Arm Angle/Pitch Movement Plots!"),
  
  sidebarLayout(
    sidebarPanel(
      width = 3,
      selectInput("dataset", "Select Dataset:",
                  choices = c("2023 Data" = "2023", "2024 Data" = "2024"),
                  selected = "2024"),
      selectizeInput("pitcher", "Select Pitcher:", choices = NULL),
      actionButton("update", "Submit")
    ),
    
    mainPanel(
      width = 9,
      reactableOutput("pitcher_table"),  # Changed to reactable for better UI
      
    )
  )
)

# Server
server <- function(input, output, session) {
  
  # Cache the dataset selection to avoid redundant data processing
  dataset_cached <- reactive({
    dataset <- switch(input$dataset,
                      "2023" = final_2023_with_percentile,
                      "2024" = final_2024_with_percentile)
    dataset
  }) 
  
  # Update pitcher choices based on cached dataset selection
  observe({
    dataset <- dataset_cached()
    
    updateSelectizeInput(session, "pitcher",
                         choices = unique(dataset$player_name))  # Assuming the dataset uses `player_name`
  })
  
  selected_data <- eventReactive(input$update,{
    dataset <- dataset_cached()
    
    filtered_data <- dataset %>%
      filter(player_name == isolate(input$pitcher)) %>%
      select(
        Pitcher = player_name,
        `Pitch Type` = api_pitch_type,
        `Horizontal Break`,
        `Induced Vertical Break`,
        `Pitch Velocity`,
        Usage = pitch_usage,
        `Arm Angle` = avg_arm_angle,
        `xArm Angle` = expected_arm_angle,
        Delta = difference,
        `Percentile Difference` = difference_percentile  # Include the difference_percentile column
      )
    
    if (nrow(filtered_data) == 0) {
      return(NULL)  # Return NULL if no data for the selected pitcher
    }
    
    return(filtered_data)
  }) 
  
  
  output$pitcher_name <- renderText({
    paste("Pitcher:", input$pitcher)
  })
  
  output$pitcher_table <- renderReactable({
    data <- selected_data()
    
    if (is.null(data)) {
      return(data.frame())  # Return an empty data frame if no data is selected
    }
    
    # Round all numeric columns to 1 decimal place
    data <- data %>% mutate(across(where(is.numeric), ~ round(.x, 1)))
    
    reactable::reactable(data, pagination = TRUE)  # Interactive table
  }) 
  
  
}

# Run the app
shinyApp(ui = ui, server = server)
  • 1 respostas
  • 23 Views
Martin Hope
firmo23
Asked: 2024-10-08 05:45:07 +0800 CST

Como alternar um conjunto de dados dependendo do valor de um selectInput?

  • 5

Tenho o shinyaplicativo abaixo no qual preciso alternar entre os dois conjuntos de dados, mas até agora só consigo o de 2024.

library(shiny)
library(ggplot2)
library(dplyr)
library(glue)
library(reactable)
final_2023_with_percentile <- structure(list(player_name = c("Abbott, Andrew", "Abbott, Andrew", 
                                                             "Abbott, Andrew", "Abbott, Andrew", "Abreu, Bryan"), api_pitch_type = c("CH", 
                                                                                                                                     "CU", "FF", "ST", "FF"), `Horizontal Break` = c(14.5784810126582, 
                                                                                                                                                                                     -8.75646017699115, 7.72310797174571, -11.787027027027, -7.55102362204724
                                                                                                                                     ), `Induced Vertical Break` = c(10.763164556962, -3.3975221238938, 
                                                                                                                                                                     16.3276286579213, 5.79423423423423, 16.278188976378), `Pitch Velocity` = c(86.6278481012658, 
                                                                                                                                                                                                                                                80.8719764011799, 92.7466195761857, 82.9141141141141, 97.5663385826772
                                                                                                                                                                     ), pitch_usage = c(15.959595959596, 17.1212121212121, 50.050505050505, 
                                                                                                                                                                                        16.8181818181818, 41.1336032388664), avg_arm_angle = c(44.6095238095238, 
                                                                                                                                                                                                                                               49.552380952381, 45.7190476190476, 43.8, 40.1347222222222), pitch_group = c("Offspeed", 
                                                                                                                                                                                                                                                                                                                           "Breaking", "Fastball", "Breaking", "Fastball"), year = c(2023, 
                                                                                                                                                                                                                                                                                                                                                                                     2023, 2023, 2023, 2023), expected_arm_angle = c(45.3313248212314, 
                                                                                                                                                                                                                                                                                                                                                                                                                                     48.0091346481901, 43.3291879571372, 45.1739731517787, 42.3795663314202
                                                                                                                                                                                                                                                                                                                                                                                     ), difference = c(-0.721801011707591, 1.54324630419084, 2.38985966191041, 
                                                                                                                                                                                                                                                                                                                                                                                                       -1.3739731517787, -2.24484410919793), difference_percentile = c(11, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                       36, 61, 32, 59)), row.names = c(NA, -5L), class = c("tbl_df", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           "tbl", "data.frame"))
final_2024_with_percentile <- structure(list(player_name = c("Abbott, Andrew", "Abbott, Andrew", 
                                                             "Abbott, Andrew", "Abbott, Andrew", "Abreu, Bryan"), api_pitch_type = c("CH", 
                                                                                                                                     "CU", "FF", "ST", "FF"), `Horizontal Break` = c(14.8485, -8.75612903225807, 
                                                                                                                                                                                     8.8715142198309, -12.5934841628959, -6.10478571428571), `Induced Vertical Break` = c(12.4713, 
                                                                                                                                                                                                                                                                          -4.08215053763441, 16.2903920061491, 4.45031674208145, 16.6883571428571
                                                                                                                                                                                     ), `Pitch Velocity` = c(84.73375, 80.7849462365591, 92.7887009992314, 
                                                                                                                                                                                                             82.9180995475113, 96.6285714285714), pitch_usage = c(16.4812525751957, 
                                                                                                                                                                                                                                                                  11.495673671199, 53.6052740008241, 18.2117840955913, 46.6666666666667
                                                                                                                                                                                                             ), avg_arm_angle = c(43.508, 48.376, 44.82, 44.376, 43.0328947368421
                                                                                                                                                                                                             ), pitch_group = c("Offspeed", "Breaking", "Fastball", "Breaking", 
                                                                                                                                                                                                                                "Fastball"), year = c(2024, 2024, 2024, 2024, 2024), expected_arm_angle = c(45.5588206160552, 
                                                                                                                                                                                                                                                                                                            49.1467520143948, 43.9438816766548, 46.2666308980996, 41.945208160932
                                                                                                                                                                                                                                ), difference = c(-2.0508206160552, -0.770752014394823, 0.876118323345224, 
                                                                                                                                                                                                                                                  -1.8906308980996, 1.08768657591006), difference_percentile = c(44, 
                                                                                                                                                                                                                                                                                                                 19, 24, 43, 30)), row.names = c(NA, -5L), class = c("tbl_df", 
                                                                                                                                                                                                                                                                                                                                                                     "tbl", "data.frame"))


# UI
ui <- fluidPage(
  titlePanel("Arm Angle/Pitch Movement Plots!"),
  
  sidebarLayout(
    sidebarPanel(
      width = 3,
      selectInput("dataset", "Select Dataset:",
                  choices = c("2023 Data" = "2023", "2024 Data" = "2024"),
                  selected = "2024"),
      selectizeInput("pitcher", "Select Pitcher:", choices = NULL)
    ),
    
    mainPanel(
      width = 9,
      reactableOutput("pitcher_table"),  # Changed to reactable for better UI
      
    )
  )
)

# Server
server <- function(input, output, session) {
  
  # Cache the dataset selection to avoid redundant data processing
  dataset_cached <- reactive({
    dataset <- switch(input$dataset,
                      "2023" = final_2023_with_percentile,
                      "2024" = final_2024_with_percentile)
    dataset
  }) %>% bindCache(input$dataset)
  
  # Update pitcher choices based on cached dataset selection
  observe({
    dataset <- dataset_cached()
    
    updateSelectizeInput(session, "pitcher",
                         choices = unique(dataset$player_name))  # Assuming the dataset uses `player_name`
  })
  
  selected_data <- reactive({
    dataset <- dataset_cached()
    
    filtered_data <- dataset %>%
      filter(player_name == input$pitcher) %>%
      select(
        Pitcher = player_name,
        `Pitch Type` = api_pitch_type,
        `Horizontal Break`,
        `Induced Vertical Break`,
        `Pitch Velocity`,
        Usage = pitch_usage,
        `Arm Angle` = avg_arm_angle,
        `xArm Angle` = expected_arm_angle,
        Delta = difference,
        `Percentile Difference` = difference_percentile  # Include the difference_percentile column
      )
    
    if (nrow(filtered_data) == 0) {
      return(NULL)  # Return NULL if no data for the selected pitcher
    }
    
    return(filtered_data)
  }) %>% bindCache(input$pitcher)
  
  
  output$pitcher_name <- renderText({
    paste("Pitcher:", input$pitcher)
  })
  
  output$pitcher_table <- renderReactable({
    data <- selected_data()
    
    if (is.null(data)) {
      return(data.frame())  # Return an empty data frame if no data is selected
    }
    
    # Round all numeric columns to 1 decimal place
    data <- data %>% mutate(across(where(is.numeric), ~ round(.x, 1)))
    
    reactable::reactable(data, pagination = TRUE)  # Interactive table
  }) %>% bindCache(input$pitcher)
  
  
}

# Run the app
shinyApp(ui = ui, server = server)
  • 1 respostas
  • 42 Views
Martin Hope
firmo23
Asked: 2024-09-27 20:05:40 +0800 CST

Ocultar código exibido inicialmente do aplicativo modularizado brilhante após clicar em actionButton

  • 5

Quero criar um aplicativo brilhante modularizado que inicialmente exibirá texto, mas o ocultará após clicar em actionButton(). Agora o texto sempre permanece. Meu código:

(aplicativo R)

library(shiny)
library(shinyjs)
library(shinydashboard)
library(shinyWidgets)
library(dplyr)

# Load the modules
source("sideUI.R")
source("sideServer.R")
source("textUI.R")
source("textServer.R")

# Build UI & server and then run the app
ui <- dashboardPage(
  dashboardHeader(title = "Text Hiding Example"),
  dashboardSidebar(sideUI("side")),  # Sidebar with the action button
  dashboardBody(
    useShinyjs(),  # Initialize shinyjs
    textUI("textPL")  # Text UI module
  )
)

server <- function(input, output, session) {
  # Use the reactive in another module
  btn_input <- sideServer("side")
  textServer("textPL", btn = btn_input$btn)
}

shinyApp(ui, server)

textoUI.R

textUI <- function(id) {
  ns <- NS(id)
  
  tagList(
    div(
      id = ns("showtext"),
      p("This text will be hidden after clicking the button", style = "font-size: 16px; text-align: center;")
    )
  )
}

textServer.R

textServer <- function(id, btn) {
  moduleServer(
    id,
    function(input, output, session) {
      ns <- session$ns  # Namespace function

      # Observe button click event
      observeEvent(btn(), {
        shinyjs::hide(ns("showtext"))  # Hide the text with correct namespace
      })
    }
  )
}

ladoUI.R

sideUI <- function(id) {
  ns <- NS(id)
  tagList(
    actionButton(ns("action"), "Hide Text")
  )
}

servidor lateral.R

sideServer <- function(id) {
  moduleServer(
    id,
    function(input, output, session) {
      return(btn = reactive(input$action))  # Return the button input as reactive
    }
  )
}
  • 1 respostas
  • 25 Views
Martin Hope
firmo23
Asked: 2024-09-27 02:28:14 +0800 CST

Modificar mensagem pop-up no mapa do folheto

  • 5

Meus dados são:

counted<-structure(list(scientificName = c("<U+00D7>Calammophila baltica (Flugge ex Schrad.) Brand", 
"<U+00D7>Calammophila baltica (Flugge ex Schrad.) Brand", "<U+00D7>Mahoberberis neubertii (Lem.) C.K.Schneid.", 
"<U+00D7>Mahoberberis neubertii (Lem.) C.K.Schneid.", "Abacarus Keifer, 1944", 
"Abacarus Keifer, 1944", "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", 
"Abacarus Keifer, 1944", "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", 
"Abacarus Keifer, 1944", "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", 
"Abacarus Keifer, 1944", "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", 
"Abacarus acutatus Sukhareva, 1985", "Abacarus acutatus Sukhareva, 1985", 
"Abacarus acutatus Sukhareva, 1985"), verbatimScientificName = c("x Calammophila baltica", 
"x Calammophila baltica", "Mahoberberis neubertii (hort. ex Lem.) C.K. Schneid.", 
"Mahoberberis neubertii C. K. Schneid.", "Abacarus plumiger", 
"Abacarus plumiger", "Abacarus plumiger", "Abacarus plumiger", 
"Abacarus plumiger", "Abacarus plumiger", "Abacarus sp. 3 PL-2017", 
"Abacarus sp. 4 PL-2017", "Abacarus sp. 6 PL-2017", "Abacarus sp. 7 PL-2017", 
"Abacarus sp. MD-2009", "Abacarus sp. MD-2009", "Abacarus sp. MD-2009", 
"Abacarus acutatus", "Abacarus acutatus", "Abacarus acutatus"
), year = c(2006, 2006, 2004, 2004, 2007, 2007, 2008, 2008, 2009, 
2012, 2008, 2008, 2008, 2010, 2006, 2007, 2007, 2007, 2007, 2008
), decimalLatitude = c(54.369999, 54.68, 50, 50.049999, 52.110001, 
52.110001, 52.560001, 52.669998, 52.709999, 52.459999, 52.93, 
52.669998, 52.669998, 52.91, 52.279999, 52.110001, 52.27, 52.22, 
52.27, 52.470001), decimalLongitude = c(18.73, 18.719999, 19.9, 
19.916666, 17.549999, 17.57, 17.110001, 17.5, 16.25, 16.93, 15.94, 
17.5, 17.5, 17.450001, 16.59, 17.57, 16.559999, 16.56, 16.540001, 
16.93), count = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 3L, 1L, 1L, 1L, 
2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -20L), groups = structure(list(
    scientificName = c("<U+00D7>Calammophila baltica (Flugge ex Schrad.) Brand", 
    "<U+00D7>Calammophila baltica (Flugge ex Schrad.) Brand", 
    "<U+00D7>Mahoberberis neubertii (Lem.) C.K.Schneid.", "<U+00D7>Mahoberberis neubertii (Lem.) C.K.Schneid.", 
    "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", 
    "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", 
    "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", 
    "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", "Abacarus Keifer, 1944", 
    "Abacarus acutatus Sukhareva, 1985", "Abacarus acutatus Sukhareva, 1985", 
    "Abacarus acutatus Sukhareva, 1985"), verbatimScientificName = c("x Calammophila baltica", 
    "x Calammophila baltica", "Mahoberberis neubertii (hort. ex Lem.) C.K. Schneid.", 
    "Mahoberberis neubertii C. K. Schneid.", "Abacarus plumiger", 
    "Abacarus plumiger", "Abacarus plumiger", "Abacarus plumiger", 
    "Abacarus plumiger", "Abacarus sp. 3 PL-2017", "Abacarus sp. 4 PL-2017", 
    "Abacarus sp. 6 PL-2017", "Abacarus sp. 7 PL-2017", "Abacarus sp. MD-2009", 
    "Abacarus sp. MD-2009", "Abacarus sp. MD-2009", "Abacarus acutatus", 
    "Abacarus acutatus", "Abacarus acutatus"), year = c(2006, 
    2006, 2004, 2004, 2007, 2008, 2008, 2009, 2012, 2008, 2008, 
    2008, 2010, 2006, 2007, 2007, 2007, 2007, 2008), decimalLatitude = c(54.369999, 
    54.68, 50, 50.049999, 52.110001, 52.560001, 52.669998, 52.709999, 
    52.459999, 52.93, 52.669998, 52.669998, 52.91, 52.279999, 
    52.110001, 52.27, 52.22, 52.27, 52.470001), .rows = structure(list(
        1L, 2L, 3L, 4L, 5:6, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 
        14L, 15L, 16L, 17L, 18L, 19L, 20L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -19L), .drop = TRUE))

mas estou tentando criar a mensagem pop-up com o número de contagem com:

library(leaflet)
library(dplyr)

leaflet(data = counted) %>% addTiles() %>%
          addMarkers(~decimalLongitude,~decimalLatitude, popup = ~as.character(paste("Name:",scientificName,"-","Count:",count,sep="\n")))%>%
          setView(lng = 19.0, lat = 52.0, zoom = 6)  # Center over Poland

e obtenha:

Warning: Error in eval: object 'Count' not found
  • 1 respostas
  • 23 Views
Martin Hope
firmo23
Asked: 2024-07-27 20:41:03 +0800 CST

Desative o actionButton com base na seleção de entrada dos widgets brilhantes

  • 6

Eu tenho o aplicativo brilhante abaixo e quero:

1.Quando o aplicativo é carregado pela primeira vez, os widgets não devem ter seleções e os botões de ação devem estar desativados.

2.Quando um distrito for selecionado, atualize as opções de escola.

3.Ative o botão de ação "Visualizar" quando pelo menos uma escola for selecionada.

4.Ative o botão de ação "Download" somente após clicar em "Visualizar".

5.Se todas as seleções forem desmarcadas, ambos os botões de ação deverão ser desativados novamente.

Fiz todos eles funcionarem, exceto que o botão Visualizar é inicialmente ativado e, se todas as seleções forem desmarcadas, o botão Visualizar é desativado novamente.

library(renv)
# library(AzureRMR)
# library(AzureStor)
#source(here::here("code/functions/momentmn_functions.R"))
library(dplyr)
library(shiny)
library(shinyWidgets)
library(DT)
library(tidyr)

early <- structure(list(district_name = c("Nonpublic School", "Nonpublic School", 
                                          "Nonpublic School", "Nonpublic School", "Nonpublic School", "Nonpublic School", 
                                          "Nonpublic School", "Nonpublic School", "Nonpublic School", "Nonpublic School", 
                                          "Nonpublic School", "Nonpublic School", "Nonpublic School", "Nonpublic School", 
                                          "Nonpublic School", "Nonpublic School", "Nonpublic School", "Nonpublic School", 
                                          "Nonpublic School", "Nonpublic School", "Nonpublic School", "Nonpublic School", 
                                          "Nonpublic School", "Nonpublic School", "Nonpublic School", "Nonpublic School", 
                                          "Nonpublic School", "Aitkin Public School District", "Minneapolis Public School Dist.", 
                                          "Minneapolis Public School Dist."), school_name_unique = c("Ascension Catholic School 0001-33-012", 
                                                                                                     "Risen Christ 0001-33-015", "St. Helena Catholic School 0001-33-036", 
                                                                                                     "Al-Amal School 0014-31-006", "St. Mary's Mission 0038-31-001", 
                                                                                                     "St. Joseph 0110-31-001", "Immanuel Lutheran School 0113-31-100", 
                                                                                                     "St. Joseph's Catholic 0196-31-007", "St. John The Baptist 0200-31-002", 
                                                                                                     "Our Lady Of Grace 0273-31-007", "St. Henry 0549-31-001", "St. Paul's Lutheran 0549-31-002", 
                                                                                                     "Talmud Torah 0625-31-879", "St. Dominic School 0659-31-012", 
                                                                                                     "Hills Christian 0671-31-001", "St. Paul's Lutheran 0719-31-003", 
                                                                                                     "St. Elizabeth Ann Seton School 0742-31-020", "Prince Of Peace Lutheran School 0742-31-022", 
                                                                                                     "St. Francis Xavier 0748-31-001", "Community Christian 0912-31-001", 
                                                                                                     "Fond Du Lac Ojibwe School 1094-34-030", "Bug-O-Nay-Ge-Shig 1115-34-010", 
                                                                                                     "Circle Of Life 1435-34-010", "Nay-Ah-Shing 1480-34-010", "Sacred Heart Area School 2170-31-001", 
                                                                                                     "St. Anne's 2397-31-001", "St. Mary Of Mt. Carmel 2753-31-002", 
                                                                                                     "Rippleside Elementary 0001-01-002", "Armatage Elementary 0001-03-103", 
                                                                                                     "Lake Harriet Lower Elementary 0001-03-104")), row.names = c(NA, 
                                                                                                                                                                  -30L), spec = structure(list(cols = list(temp_record_id = structure(list(), class = c("collector_character", 
                                                                                                                                                                                                                                                        "collector")), district_number = structure(list(), class = c("collector_character", 
                                                                                                                                                                                                                                                                                                                     "collector")), district_type = structure(list(), class = c("collector_character", 
                                                                                                                                                                                                                                                                                                                                                                                "collector")), school_number = structure(list(), class = c("collector_character", 
                                                                                                                                                                                                                                                                                                                                                                                                                                           "collector")), grade = structure(list(), class = c("collector_character", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              "collector")), subject = structure(list(), class = c("collector_character", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   "collector")), group_category = structure(list(), class = c("collector_character", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               "collector")), student_group = structure(list(), class = c("collector_character", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          "collector")), school_year = structure(list(), class = c("collector_double", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   "collector")), denominator = structure(list(), class = c("collector_double", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            "collector")), numerator = structure(list(), class = c("collector_double", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   "collector"))), default = structure(list(), class = c("collector_guess", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         "collector")), delim = ","), class = "col_spec"), class = c("spec_tbl_df", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     "tbl_df", "tbl", "data.frame"))

all_districts <- unique(sort(early$district_name))
all_schools <- unique(sort(early$school_name_unique))

# Define UI for application that draws a histogram
ui <- fluidPage(
  
  # Application title
  titlePanel("EPC Civic Infrastructure Assessment File Prep"),
  
  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
      h2("Select Schools to Include"),
      shinyWidgets::pickerInput(inputId = "districts",
                                label = "Districts:",
                                choices = all_districts,
                                options = list(`actions-box` = TRUE),
                                multiple = TRUE),
      shinyWidgets::pickerInput(inputId = "schools",
                                label = "Schools:",
                                choices = "",
                                options = list(`actions-box` = TRUE),
                                selected = "",
                                multiple = TRUE),
      shiny::actionButton(inputId = "runButton", label = "Preview", disabled = TRUE),
      shiny::actionButton(inputId = "downButton", label = "Download", disabled = TRUE)),
    
    # Show a plot of the generated distribution
    mainPanel(
      dataTableOutput("early_reading")#,
      
    )
  )
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {
  shiny::observeEvent(input$districts, {
    if(!is.null(input$districts) && length(input$districts) > 0){
      shinyWidgets::updatePickerInput(session = session, inputId = "schools",
                                      choices = early %>% dplyr::arrange(district_name, school_name_unique) %>% dplyr::filter(district_name %in% input$districts) %>% dplyr::select(school_name_unique) %>% unique() %>% pull())
    } else {
      shinyWidgets::updatePickerInput(session = session, inputId = "schools",
                                      choices = "",
                                      options = list(`actions-box` = TRUE),
                                      selected = "")
      shiny::updateActionButton(session, "runButton", disabled = TRUE)
      shiny::updateActionButton(session, "downButton", disabled = TRUE)
    }
  }, ignoreNULL = FALSE)
  
  shiny::observeEvent(input$schools, {
    if(!is.null(input$schools) && length(input$schools) > 0){
      shiny::updateActionButton(inputId = "runButton",
                                disabled = FALSE)
    } else {
      shiny::updateActionButton(inputId = "runButton",
                                disabled = TRUE)
      shiny::updateActionButton(inputId = "downButton",
                                disabled = TRUE)
    }
  }, ignoreNULL = FALSE)  
  
  shiny::observeEvent(input$runButton, {
    if(input$runButton > 0){
      shiny::updateActionButton(inputId = "downButton",
                                disabled = FALSE)
    }
  })
  
  output$early_reading <- renderDataTable({
    
    if(input$runButton == 0){return()}
    else{
      
      early <- early %>%
        dplyr::filter(district_name %in% input$districts, school_name_unique %in% input$schools)
      
      datatable(early)
      
    }
  })
}

# Run the application 
shinyApp(ui = ui, server = server)
  • 1 respostas
  • 24 Views
Martin Hope
firmo23
Asked: 2024-05-23 21:06:44 +0800 CST

Mantenha a ordem das linhas da coluna do quadro de dados mesclado igual às linhas da coluna comum dos 2 quadros de dados iniciais

  • 6

Eu tenho 2 dataframes que mesclo com base em uma coluna comum. O que eu quero é que a ordem das linhas do novo dataframe seja primeiro a ordem de alltr Attribute Namee depois a de allev.Não em ordem alfabética e sem a necessidade de definir a ordem manualmente após a fusão. Portanto, a ordem da coluna Nome do Atributo na nova deve serAge, Gender, Income, Area

# Sample dataframes
alltr <- data.frame(
  `Attribute Name` = c("Age", "Gender"),
  Value_x = c(254, 100)
)

allev <- data.frame(
  `Attribute Name` = c("Income", "Area"),
  Value_y = c(708, 500)
)

# Merging the dataframes
merged_df2 <- merge(alltr, allev, by = "Attribute Name", all = TRUE)
  • 1 respostas
  • 16 Views
Martin Hope
firmo23
Asked: 2024-05-20 03:57:09 +0800 CST

Use visnetwork para recriar a árvore hierárquica

  • 6

Estou tentando usar o pacote visNetwork para recriar a árvore hierárquica abaixo, como você pode ver na imagem, mas não consigo definir a hierarquia para as posições.

# Install and load the visNetwork package
install.packages("visNetwork")
library(visNetwork)
# Create nodes data frame
nodes <- data.frame(
  id = 1:7,
  label = c("BLADDER", "TRODELVY", "EV", "NO ADC RECEIVED", "EV", "NO ADC RECEIVED", "TRODELVY "),
  color = c("gray", "red", "blue", "gray", "blue", "gray", "red"),
  shape = "box"
)

# Create edges data frame
edges <- data.frame(
  from = c(1, 1, 2, 2, 3, 3),
  to = c(2, 3, 4, 5, 6, 7)
)

# Create the network visualization
visNetwork(nodes, edges) %>%
  visNodes(shape = "box") %>%
  visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)%>%
  visPhysics(solver = "hierarchicalRepulsion", 
             forceAtlas2Based = list(gravitationalConstant = -500))

insira a descrição da imagem aqui

  • 1 respostas
  • 12 Views
Martin Hope
firmo23
Asked: 2024-04-19 22:45:37 +0800 CST

Altere a cor do ícone com base na entrada numérica em um aplicativo brilhante

  • 6

Eu tenho um aplicativo brilhante no qual quero que a seta fique vermelha quando o valor for negativo e verde quando o valor for positivo, se o valor for 0, será preto.

library(shiny)
library(shinydashboard)
library(fontawesome)
# Define UI 
ui <- fluidPage(
  
  # Application title
  titlePanel("Numeric Input App"),
  
  # Sidebar layout with input and output definitions
  sidebarLayout(
    
    # Sidebar panel for inputs
    sidebarPanel(
      numericInput("number", "Enter a number:", value = 0)  # Numeric input field
    ),
    
    # Main panel for displaying output
    mainPanel(
      box(
        width=8,title = "ABT",status="primary",solidHeader = T,
        fluidRow(
          column(12,textOutput("output"),
                 column(2,fa("arrow-trend-up", fill = "forestgreen"))
          )
          
        ))
    )
  )
)

# Define server logic
server <- function(input, output) {
  
  # Function to render the output based on user input
  output$output <- renderText({
    paste("You entered:", input$number)  # Display the entered number
  })
}

# Run the application 
shinyApp(ui = ui, server = server)
  • 1 respostas
  • 19 Views
Martin Hope
firmo23
Asked: 2024-04-17 20:19:24 +0800 CST

Índice xts de subconjunto com base no intervalo de datas em um aplicativo brilhante

  • 6

No shinyaplicativo abaixo, estou tentando subdividir o objeto xts e, portanto, o gráfico com base no intervalo de datas, mas enquanto o gráfico inicial é criado, recebo Aesthetics must be either length 1 or the same as the data (2514).

## app.R ##
library(shiny)
library(shinydashboard)
library("vctrs")
library("xts")
library('quantmod')
library('tseries')
library('forecast')
library('ggplot2')
library('reshape2')
library(stats)
library(forecast)
library(shinyWidgets)


ABT <- getSymbols(Symbols = "ABT", src = "yahoo", from = Sys.Date() - 20*365, 
                  to = Sys.Date(), auto.assign = FALSE)

# Select only Close price
ABT <- Cl(ABT)

ABV<- getSymbols(Symbols = "ABV", src = "yahoo", from = Sys.Date() - 20*365, 
                 to = Sys.Date(), auto.assign = FALSE)
ABV <- Cl(ABV)

SP500 <- getSymbols(Symbols = "^GSPC", src = "yahoo", from = Sys.Date() - 20*365, 
                    to = Sys.Date(), auto.assign = FALSE)
SP500<-Cl(SP500)
Dow_J <- getSymbols("^DJI", src = "yahoo", from = Sys.Date() - 20*365, 
                    to = Sys.Date(), auto.assign = FALSE)
Dow_J<-Cl(Dow_J)

# Assuming your xts object is named 'my_xts'
first_row_name <- index(ABT)[1]
last_row_name <- index(ABT)[nrow(ABT)]

ui <- dashboardPage(
  dashboardHeader(title = "Share price prediction and movement"),
  dashboardSidebar(
    
    dateRangeInput('dateRange',
                   label = 'Date range',
                   start = first_row_name , end = Sys.Date() 
    )
    
  ),
  dashboardBody(
    
    fluidRow(
      column(12,
             plotOutput("plot2")
      )
    )
  )
)

server <- function(input, output) { 
  
  output$plot2<-renderPlot({
    spf_dw_data <- merge(SP500, Dow_J)
    spf_dw_data<-subset(spf_dw_data, index(spf_dw_data) >= input$dateRange[1] & index(spf_dw_data) <= input$dateRange[2])
    DateSJ <- index(spf_dw_data)
    
    ggplot(spf_dw_data, aes(x=DateSJ)) +
      geom_line(aes(y = SP500, color = "S&P 500"), size = 1) +
      geom_line(aes(y = Dow_J, color = "Dow Jones"), size = 1) +
      labs(title = "Stock Prices Over Time",
           y = "Adjusted Close Price",
           color = "Company") +
      theme_minimal()
    
  })
  
  
}

shinyApp(ui, server)
  • 1 respostas
  • 20 Views
Martin Hope
firmo23
Asked: 2024-01-08 17:03:20 +0800 CST

Converta dados do formato largo para o formato longo, verificando os valores de uma linha

  • 6

tenho os dados abaixo

data<-structure(list(id = c("R_88j7lG37gLfxk22", "R_6DK8lERVf8lSQf4"
), t1_choice = c("2", "3"), t2_choice = c("1", "3"), t3_choice = c("1", 
"2"), t4_choice = c("2", "1")), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame")) 

esta é a primeira linha dos meus dados:

insira a descrição da imagem aqui

e quero convertê-lo para um formato longo como abaixo com esta lógica. Para cada participante existem 12 linhas, porque existem 4 tarefas (4 't's) e 3 perfis em cada tarefa (3 'p's). A coluna de escolha é um binário onde é 1 se o perfil naquela linha foi escolhido naquela tarefa e 0 se não foi, que é informação contida nas colunas 'tN_choice'.

insira a descrição da imagem aqui

meu método está errado

tasks<-4
profiles<-3
#column position of first task
cpft<-2

#column position of last task
cplt<-5

# Extracting choices
choices <- as.numeric(unlist(long[, cpft:cplt]))

# Create the new dataframe with id and choice columns
new_df <- data.frame(
  id = rep(data$id, each = tasks*profiles),
  choice = rep(0, times = length(id))
)

# Replacing values based on original choices
for (i in 1:(tasks*profiles)) {
  idx <- (i - 1) * profiles + choices[i]
  new_df$choice[idx] <- 1
}
  • 1 respostas
  • 103 Views
Martin Hope
firmo23
Asked: 2024-01-07 22:54:29 +0800 CST

Aplique o processo de dados a todas as linhas do conjunto de dados usando um loop for()

  • 6

Eu tenho esse dataframe vazio

new_df<-structure(list(id = c("R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
"R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
"R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
"R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", "R_88j7lG37gLfxk22", 
"R_88j7lG37gLfxk22", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
"R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
"R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
"R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", "R_6DK8lERVf8lSQf4", 
"R_6DK8lERVf8lSQf4"), choice = c(0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 
1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1), low_env = c(NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA), mid_env = c(NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA), high_env = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), low_eth = c(NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA), mid_eth = c(NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA), high_eth = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), 
    `low_pri($25)` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), 
    `mid_pri($75)` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), 
    `high_pri($125)` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
    )), row.names = c(NA, 24L), class = "data.frame")

e com os dados e código acima preencho metade dele com base na primeira linha do longconjunto de dados. Como posso usar um for()loop para aplicar esse método ao restante das linhas do longconjunto de dados que preencherão a outra metade?

long<-structure(list(id = c("R_88j7lG37gLfxk22", "R_6DK8lERVf8lSQf4"
), t1_choice = c("2", "3"), t2_choice = c("1", "3"), t3_choice = c("1", 
"2"), t4_choice = c("2", "1"), t1_p1_env = c("high_env", "mid_env"
), t1_p1_eth = c("low_eth", "mid_eth"), t1_p1_pri = c("$125", 
"$25"), t1_p2_env = c("mid_env", "high_env"), t1_p2_eth = c("high_eth", 
"low_eth"), t1_p2_pri = c("$25", "$75"), t1_p3_env = c("low_env", 
"low_env"), t1_p3_eth = c("mid_eth", "low_eth"), t1_p3_pri = c("$75", 
"$75"), t2_p1_env = c("high_env", "mid_env"), t2_p1_eth = c("low_eth", 
"high_eth"), t2_p1_pri = c("$75", "$125"), t2_p2_env = c("mid_env", 
"low_env"), t2_p2_eth = c("mid_eth", "low_eth"), t2_p2_pri = c("$125", 
"$75"), t2_p3_env = c("mid_env", "high_env"), t2_p3_eth = c("mid_eth", 
"high_eth"), t2_p3_pri = c("$75", "$75"), t3_p1_env = c("high_env", 
"mid_env"), t3_p1_eth = c("high_eth", "mid_eth"), t3_p1_pri = c("$125", 
"$125"), t3_p2_env = c("mid_env", "high_env"), t3_p2_eth = c("low_eth", 
"low_eth"), t3_p2_pri = c("$25", "$25"), t3_p3_env = c("low_env", 
"low_env"), t3_p3_eth = c("high_eth", "high_eth"), t3_p3_pri = c("$25", 
"$75"), t4_p1_env = c("low_env", "high_env"), t4_p1_eth = c("low_eth", 
"low_eth"), t4_p1_pri = c("$75", "$125"), t4_p2_env = c("high_env", 
"mid_env"), t4_p2_eth = c("mid_eth", "mid_eth"), t4_p2_pri = c("$125", 
"$25"), t4_p3_env = c("low_env", "low_env"), t4_p3_eth = c("high_eth", 
"mid_eth"), t4_p3_pri = c("$25", "$125")), row.names = c(NA, 
-2L), class = c("tbl_df", "tbl", "data.frame"))

#working
# Loop through the first three rows of new_df
for (i in 1:3) {
  # Extracting the required values from long1 for each row
  env <- long[1,][paste0("t1_p", i, "_env")][1]
  eth <- long[1,][paste0("t1_p", i, "_eth")][1]
  pri <- long[1,][paste0("t1_p", i, "_pri")][1]
  
  # Matching values from long[1,] to new_df columns in the corresponding row
  new_df[i, "low_env"] <- as.numeric(env == "low_env")
  new_df[i, "mid_env"] <- as.numeric(env == "mid_env")
  new_df[i, "high_env"] <- as.numeric(env == "high_env")
  new_df[i, "low_eth"] <- as.numeric(eth == "low_eth")
  new_df[i, "mid_eth"] <- as.numeric(eth == "mid_eth")
  new_df[i, "high_eth"] <- as.numeric(eth == "high_eth")
  new_df[i, "low_pri($25)"] <- as.numeric(pri == "$25")
  new_df[i, "mid_pri($75)"] <- as.numeric(pri == "$75")
  new_df[i, "high_pri($125)"] <- as.numeric(pri == "$125")
}

# Loop through the second three rows of new_df
for (i in 1:3) {
  # Extracting the required values from long[1,] for each row
  env <- long[1,][paste0("t2_p", i, "_env")][1]
  eth <- long[1,][paste0("t2_p", i, "_eth")][1]
  pri <- long[1,][paste0("t2_p", i, "_pri")][1]
  
  # Matching values from long[1,] to new_df columns in the corresponding row
  new_df[i + 3, "low_env"] <- as.numeric(env == "low_env")
  new_df[i + 3, "mid_env"] <- as.numeric(env == "mid_env")
  new_df[i + 3, "high_env"] <- as.numeric(env == "high_env")
  new_df[i + 3, "low_eth"] <- as.numeric(eth == "low_eth")
  new_df[i + 3, "mid_eth"] <- as.numeric(eth == "mid_eth")
  new_df[i + 3, "high_eth"] <- as.numeric(eth == "high_eth")
  new_df[i + 3, "low_pri($25)"] <- as.numeric(pri == "$25")
  new_df[i + 3, "mid_pri($75)"] <- as.numeric(pri == "$75")
  new_df[i + 3, "high_pri($125)"] <- as.numeric(pri == "$125")
  # Adjusting the choice column
  new_df[i + 3, "choice"] <- as.numeric(long[1,][paste0("t2_choice")][1] == i)
}
  # Loop through the second three rows of new_df
  for (i in 1:3) {
    # Extracting the required values from long[1,] for each row
    env <- long[1,][paste0("t3_p", i, "_env")][1]
    eth <- long[1,][paste0("t3_p", i, "_eth")][1]
    pri <- long[1,][paste0("t3_p", i, "_pri")][1]
    
    # Matching values from long[1,] to new_df columns in the corresponding row
    new_df[i + 6, "low_env"] <- as.numeric(env == "low_env")
    new_df[i + 6, "mid_env"] <- as.numeric(env == "mid_env")
    new_df[i + 6, "high_env"] <- as.numeric(env == "high_env")
    new_df[i + 6, "low_eth"] <- as.numeric(eth == "low_eth")
    new_df[i + 6, "mid_eth"] <- as.numeric(eth == "mid_eth")
    new_df[i + 6, "high_eth"] <- as.numeric(eth == "high_eth")
    new_df[i + 6, "low_pri($25)"] <- as.numeric(pri == "$25")
    new_df[i + 6, "mid_pri($75)"] <- as.numeric(pri == "$75")
    new_df[i + 6, "high_pri($125)"] <- as.numeric(pri == "$125")
    # Adjusting the choice column
    new_df[i + 6, "choice"] <- as.numeric(long[1,][paste0("t3_choice")][1] == i)
  }
for (i in 1:3) {
  # Extracting the required values from long[1,] for each row
  env <- long[1,][paste0("t4_p", i, "_env")][1]
  eth <- long[1,][paste0("t4_p", i, "_eth")][1]
  pri <- long[1,][paste0("t4_p", i, "_pri")][1]
  
  # Matching values from long[1,] to new_df columns in the corresponding row
  new_df[i + 9, "low_env"] <- as.numeric(env == "low_env")
  new_df[i + 9, "mid_env"] <- as.numeric(env == "mid_env")
  new_df[i + 9, "high_env"] <- as.numeric(env == "high_env")
  new_df[i + 9, "low_eth"] <- as.numeric(eth == "low_eth")
  new_df[i + 9, "mid_eth"] <- as.numeric(eth == "mid_eth")
  new_df[i + 9, "high_eth"] <- as.numeric(eth == "high_eth")
  new_df[i + 9, "low_pri($25)"] <- as.numeric(pri == "$25")
  new_df[i + 9, "mid_pri($75)"] <- as.numeric(pri == "$75")
  new_df[i + 9, "high_pri($125)"] <- as.numeric(pri == "$125")
  

  # Adjusting the choice column
  new_df[i + 9, "choice"] <- as.numeric(long[1,][paste0("t4_choice")][1] == i)
}

resultado esperado

insira a descrição da imagem aqui

  • 3 respostas
  • 94 Views
Martin Hope
firmo23
Asked: 2023-12-30 22:33:18 +0800 CST

Atualize pares de widgets brilhantes que afetam uns aos outros

  • 5

Tenho o shinyaplicativo abaixo em que o subconjunto inicial acontece a partir da 1ª entrada com os nomes. Então os valores disponíveis deverão passar para as outras quatro entradas e para a tabela.

Quero que os valores das outras 4 entradas sejam atualizados com base na escolha da primeira, mas também quando, por exemplo, eu selecionar o valor mínimo ou máximo, as datas mínima e máxima serão subdefinidas e vice-versa.

Apenas a 1ª entrada deve manter sempre a mesma quantidade de todos os nomes.

library(shiny)
library(shinydashboard)
library(shinyWidgets)
# Load necessary libraries
library(DT)

# Creating a sample dataframe
set.seed(123)
dates <- seq(as.Date("2023-01-01"), as.Date("2023-12-31"), by = "days")
numeric_values <- sample(1:100, length(dates), replace = TRUE)
names <- rep(c("Alice", "Bob", "Charlie"), length.out = length(dates))

df <- data.frame(Date = dates, Numeric = numeric_values, Name = names)

# Define UI
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      pickerInput("namePicker", "Select Name:", choices = unique(df$Name),selected = unique(df$Name)[1], multiple = TRUE),
      uiOutput("numeric1"),
      uiOutput("numeric2"),
      uiOutput("date1"),
      uiOutput("date2")
    ),
    mainPanel(
      DTOutput("table")
    )
  )
)

# Define server logic
server <- function(input, output, session) {
  
  # Filter data based on selected names
  filtered_data <- reactive({
    req(input$namePicker)
    df_subset <- df[df$Name %in% input$namePicker, ]
    
    return(df_subset)
  })
  
  # Render the filtered data table
  output$table <- renderDT({
    datatable(filtered_data(), options = list(pageLength = 10))  # Customize datatable appearance if needed
  })
  
  # Render numeric range inputs dynamically
  output$numeric1 <- renderUI({
    numericInput("minNumeric", "Min Numeric Value:", min = min(df$Numeric), max = max(df$Numeric), value = min(df$Numeric))
  })
  output$numeric2 <- renderUI({
    numericInput("maxNumeric", "Max Numeric Value:", min = min(df$Numeric), max = max(df$Numeric), value = max(df$Numeric))
  })
  # Render date range inputs dynamically
  output$date1 <- renderUI({
    dateInput("minDate", "Min Date:", min = min(df$Date), max = max(df$Date), value = min(df$Date))
  })
  output$date2 <- renderUI({
    dateInput("maxDate", "Max Date:", min = min(df$Date), max = max(df$Date), value = max(df$Date))
  })
}

# Run the application
shinyApp(ui = ui, server = server)
  • 2 respostas
  • 71 Views
Martin Hope
firmo23
Asked: 2023-12-11 19:54:35 +0800 CST

Faça a escolha de um widget brilhante desabilitado para os outros 3 widgets brilhantes

  • 5

Tenho o shinyaplicativo abaixo com 4 entradas. Eles contêm todas as variáveis ​​do mtcarsconjunto de dados. Agora quero que se um valor selecionado por exemplo em uma entrada (por exemplo mpg na 1ª) esse valor não possa ser escolhido em nenhuma outra entrada. Portanto, toda vez que essas 4 entradas terão um valor diferente selecionado.

library(shiny)
library(shinydashboard)

choices <- c("Pop", "RC", "RT","R4")

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    selectInput("Pr", "Select the price for analysis", choices = choices, multiple = F, selected = choices[1]),
    selectInput("Pr2", "Select the price for analysis", choices = choices, multiple = F, selected = choices[2]),
    selectInput("Pr3", "Select the price for analysis", choices = choices, multiple = F, selected = choices[3]),
    selectInput("Pr4", "Select the price for analysis", choices = choices, multiple = F, selected = choices[4])
    
  ),
  dashboardBody()
)

server <- function(input, output, session) {
  observeEvent(input$Pr, {
    updateSelectInput(session, "Pr2", choices = choices[!choices %in% input$Pr])
  })
  observeEvent(input$Pr3, {
    updateSelectInput(session, "Pr2", choices = choices[!choices %in%input$Pr3])
  })
  observeEvent(input$Pr4, {
    updateSelectInput(session, "Pr2", choices = choices[!choices %in%input$Pr4])
  })
  observeEvent(input$Pr2, {
    updateSelectInput(session, "Pr", choices = choices[!choices %in% input$Pr2])
  })
  observeEvent(input$Pr3, {
    updateSelectInput(session, "Pr", choices = choices[!choices %in% input$Pr3])
  })
  observeEvent(input$Pr4, {
    updateSelectInput(session, "Pr", choices = choices[!choices %in% input$Pr4])
  })
  observeEvent(input$Pr, {
    updateSelectInput(session, "Pr3", choices = choices[!choices %in% input$Pr])
  })
  observeEvent(input$Pr2, {
    updateSelectInput(session, "Pr3", choices = choices[!choices %in% input$Pr2])
  })
  observeEvent(input$Pr4, {
    updateSelectInput(session, "Pr3", choices = choices[!choices %in% input$Pr4])
  })
  observeEvent(input$Pr, {
    updateSelectInput(session, "Pr4", choices = choices[!choices %in% input$Pr])
  })
  observeEvent(input$Pr2, {
    updateSelectInput(session, "Pr4", choices = choices[!choices %in% input$Pr2])
  })
  observeEvent(input$Pr3, {
    updateSelectInput(session, "Pr4", choices = choices[!choices %in% input$Pr3])
  })
}

shinyApp(ui, server)
  • 1 respostas
  • 23 Views
Martin Hope
firmo23
Asked: 2023-12-07 23:34:57 +0800 CST

Pontos dinâmicos de cor no gráfico de dispersão permanentemente baseado no argumento de cor

  • 5

Eu tenho esse aplicativo brilhante e quero colorir os pontos no gráfico de dispersão 3D com base na data selecionada, dando-lhes sempre uma cor específica e não uma cor aleatória que mudará quando eu os esconder e depois os trouxer de volta. Mas todos os meus pontos ainda são azuis

library(shiny)
library(tidyverse)
library(plotly)
library(dplyr)

df2<-structure(list(publicationDate = structure(c(18610, 18410, 18597, 
                                             18375, 18284), class = "Date"), x = c(8.593744, 10.341268, 11.454429, 
                                                                                   10.595986, 11.012522), y = c(4.2456923, 6.767409, 5.2631335, 
                                                                                                                6.5070715, 7.6513457), z = c(5.6303487, 8.002673, 6.332502, 8.773426, 
                                                                                                                                             8.604475), influentialCitationCount = c(98.2037608756666, 100, 
                                                                                                                                                                                     37.8052203199551, 99.6632051641875, 99.1018804378333)), row.names = c(NA, 

                                                                                                                                                                                                                                                           5L), class = "data.frame")
df2 <- df2[order(df2[, 1]), ]

ui <- fluidPage(
  titlePanel("3D Scatter Plot Visualization"),
  sidebarLayout(
    sidebarPanel(
      pickerInput(inputId = "selectedDates",
                  label = "Choose Dates:",
                  
                  choices = list(Dates = as.list(unique(df2$publicationDate)),PointColor = colors()[5]),
                  selected = unique(df2$publicationDate)[1],
                  multiple = TRUE,
                  options = list(
                    `actions-box` = TRUE,
                    `deselect-all-text` = "None...",
                    `select-all-text` = "Yeah, all !",
                    `none-selected-text` = "zero"
                  ))

    ),
    mainPanel(
      plotlyOutput(outputId = "scatterPlot3D")
      
    )
  )
)

server <- function(input, output) {
  output$scatterPlot3D <- renderPlotly({
    
    # Filter data based on selected topicLabels
    df2 <- df2[df2$publicationDate %in% input$selectedDates, ]
    
    
    # Create the 3D scatter plot with bolded hover text
    scatter3Dplot <- plot_ly(data = df2, x = ~x, y = ~y, z = ~z, color = ~publicationDate,
                             type = "scatter3d", mode = "markers",
                             marker = list(size = 3)
                             ) %>%
      layout(title = "3D Scatter Plot with Wrapped Title and Custom Popup by Date",
             scene = list(
               xaxis = list(title = "X Axis"),
               yaxis = list(title = "Y Axis"),
               zaxis = list(title = "Z Axis")
             )) %>%
      layout(legend = list(orientation = "h"),
             showlegend = FALSE)
    
    
    
    return(scatter3Dplot)
  })
  
}



# Component 3: A call to the `shinyApp` function
shinyApp(ui = ui, server = server)
  • 1 respostas
  • 19 Views
Martin Hope
firmo23
Asked: 2023-11-16 01:18:56 +0800 CST

Extraia valores de intervalo de confiança de 95% do modelo Kaplan Meier

  • 4

Depois de calcular um modelo Kaplan Meier, obtenho a km_fitlista abaixo. Como posso extrair valores de intervalo de confiança de 95% agora?

# Plot Kaplan-Meier curves
sg1_survival <- Surv(
  time = sg1$`Time from breast cancer diagnosis to bone metastasis (months) (NA = unknown)`,
  event = sg1$`status (=1 as all pts have bone metastasis and BC)`
)


km_fit <- survfit(sg1_survival ~ sg1$`Molecular type (0=hr+her2+, 1=hr+her2-, 2=hr-her2+, 3=TNBC)`, data = sg1)

# Calculate 95% confidence intervals? fails with "no applicable method"
ci <- confint(km_fit, level = 0.95)
  • 2 respostas
  • 57 Views
Martin Hope
firmo23
Asked: 2023-11-15 01:15:16 +0800 CST

Converter caracteres em datas sem ter alguns deles como NAs após a conversão

  • 5

eu tenho esses dados

    sg2<-structure(list(`Last prescription/or progression time (if progressed)` = c("23-11-2021", 
"28-09-2022", "45020", "45079", "23-05-2023"), time = c(3.682191781, 
9.008219178, 22.52054795, 20.02191781, 12.7890411), status = c(0, 
0, 0, 0, 0), `Number of bone lesions (<5 = “<5”, >=5 = “≥5”) (clear, multiple bone metastases ≥5 are defined)` = c(">=5", 
"<5", ">=5", ">=5", "<5")), row.names = c(NA, -5L), class = c("tbl_df", 
"tbl", "data.frame"))

e alguns dos meus dados de datas são exibidos como 44383, por exemplo, enquanto outras datas são carregadas normalmente do meu arquivo Excel. Tento convertê-los todos para as datas abaixo, mas recebo datas como NAs

sg2$`Time of first prescription of denosumab (if enrolled in QL1206 and JMT, this time is the time of first use of XGEVA after leaving the group)` <- as.Date(as.numeric(sg2$`Time of first prescription of denosumab (if enrolled in QL1206 and JMT, this time is the time of first use of XGEVA after leaving the group)`), origin = "1899-12-30")
Warning message:
In as.Date(as.numeric(sg2$`Time of first prescription of denosumab (if enrolled in QL1206 and JMT, this time is the time of first use of XGEVA after leaving the group)`),  :
  NAs introduced by coercion
  • 1 respostas
  • 34 Views
Martin Hope
firmo23
Asked: 2023-10-19 20:48:59 +0800 CST

Substitua todos os NAs ou valores "N/A" em um conjunto de dados pela média de cada coluna existente

  • 5

No dataframe abaixo que possui colunas apenas com valores numéricos, quero encontrar ou NAs"N/A" de cada coluna e substituí-los pelo valor médio do restante das linhas de cada coluna

data <- structure(list(`Review Star` = c("N/A", "5", "5", "4", NA, "5", 
"3.4", NA), `Total Review` = c("N/A", "1", "5", "5", NA, "1", 
"5", NA)), row.names = c(NA, -8L), class = c("tbl_df", "tbl", 
"data.frame"))

library(dplyr)
data <- data %>% 
  mutate_all(~ifelse(. %in% c("N/A", "NA"), mean(., na.rm = TRUE), .))
  • 3 respostas
  • 45 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve