Olá.
Estou iniciando com R e queria fazer um filtro por país. Ao escolher o país, eu quero que o histograma mude, mas ele continua o mesmo para todos os países, mesmo eu o colocando dentro do reactive. O codigo que estou tentando é:
#ui.R
library(shiny)
library(tidyverse)
df<-read_delim('Adult.csv', delim = ',')
names(df) <- tolower(names(df))#R eh sensitive, por isso pondo todas column names em minusculo antes
ui <- fluidPage( #strong command makes the sentence bold
titlePanel(strong("Final project: Trends in Demographics and Income")),
#First line we need a list box:
fluidRow(column(width = 12, h5("Explore the difference between people who earn less than 50K and more than 50K. You can filter the data by country,
then explore various demographic information."),
wellPanel( #se essa linha abajo tivesse funcionado, seria dataset dinamico. Ver depois.
selectInput("Country", "Country", choices=unique(df$native_country)),#tentei df$dfInput e nada
))),
#Segundo fluidRow eh a segunda linha: o codigo pra mostrar 4 possibilidades de radiobutton
#agrupadas 2 a 2:
fluidRow(column(width = 3, wellPanel( h5("Choose a continuous variable between age and hours and type of graphs (histogram or boxplot) to see on the right:"),
radioButtons("AgeHour",
"Continuous",
choices = c("age", "hours_per_week")),
#o code abaixo tem os 2 ultimos radioButtons pra pessoa escolher o tipo de grafico
radioButtons("Graph",
"Graph",
choices = c("Histogram", "Boxplot")))),
#Aqui eh acoluna da direita da segunda linha, onde deve aparecer o resultado do grafico
#selecionado e de acordo com horas ou age selecionado:
column(width = 9, h5("Trend of age:", align="left"),
plotOutput("p1"), #histogram
plotOutput("p2"))), #boxplot)),
#A terceira e ultima linha desse dashboard: Lado esquerdo com 4 opcoes de radioButton e
#lado direito deve sair um Bar conforme a escolha de um desses radioButton
fluidRow(column(width = 3, wellPanel( h5("Select a categorical variable to view the bar chart on the right. Use the checkbox to view a stacked bar chart to combine
the income levels into one graph:"),
radioButtons("Bar_fill", "Categorical:",
choices = c("education", "workclass", "sex","stack bars")))),
#aqui na coluna da direita, por codigo pra aparecer graph de bar
column(width = 9, h5("Trend of workclass:", align="left"),
plotOutput("p3"))) # bar chart))
)
#server.R
library(shiny)
library(tidyverse)
library(ggplot2)
# Read in data again pq ficou carregado no Ui.R estaticamente. Por isso a chamada aqui de novo
df <- read_csv("Adult.csv") #trocar do dataset aqui pra adultos na versao final
#Convert column names to lowercase for convenience:
names(df) <- tolower(names(df))#continuar tentando em outro arquivo, fazer o filtro dinamico
server <- function(input, output) {#carrega a escolha de country estaticamente pq foi feita la no Ui.R
dfInput <- reactive({
df %>% filter(native_country == input$Country)
})
# TASK p1: Histogram (depois que funcionar pra Age, fazer o IF para os demais e os outros)
output$p1 <- renderPlot({
#df1 <- dfInput()
#verificar parametros para histograma x e y
p <- ggplot(dfInput(), aes(x = df$age)) +
labs(y = "Number of Idades/paises ??", title = paste("Trend of...", input$AgeHour))
#})#encerra a base do histo aqui qdo o if funcionar com o reactive e apaga logo embaio
# Based on radio button input, change histogram fill - copiado, corrigir todo esse if e ate a ordem das acoes
if (input$Graph == "Histogram") {
p + geom_histogram(bins = 6, fill ="red")
}
})#encerra a base do histo aqui enquanto nao funcionar o if pq o if precisa do reactive
#else {
# output$p2 <- renderPlot({#por enquanto vou por so age no lugar de !!input$continuous_variable
# ggplot(df, aes(y = !!input$continuous_variable)) +
# geom_boxplot() +
# labs(title = paste("How", input$continuous_variable, "value is spread")) +
# coord_flip()
# })#encerra o boxplot e o IF aqui, mas nao esta funcionando
#}
#Task p3: bar - Pesquisar o que eh factor e stack bar pra arrumar esse bar
output$p3 <- renderPlot({
ggplot(dfInput(),
aes(x = factor(!!input$Bar_fill),
fill = factor(!!input$Bar_fill))) +
geom_bar() +
labs(x = input$Bar_fill,
title = paste("Trend of", input$Bar_fill))
})
}
Obrigada.