将数据导入 shiny-application 时创建变量,管理接收到的数据
Creating variables when importing data into the shiny-application, managing the received data
同志们!问候。
请帮帮我...有一些重大的误解。
假设我这样创建 data.frame:
df<-data.frame(num = c(1:250),
app_num = sample(1:100, 250, replace=T),
entrance=sample(1:4, 250, replace=T),
gender=sample(c('m','f'), 250,replace=T),
age= sample(1:100, 250, replace=T))
我将其保存为“*csv”格式,使用命令:
write.csv2(data_file,file = file.choose(new = T), row.names = FALSE, quote = FALSE)
O.K。
现在我想创建一个闪亮的应用程序来显示和使用他的数据:
library("shiny")
#to work with extra string functions
library("stringr")
library("data.table")
library("readr")
# Define UI for application that draws a histogram
ui <- fluidPage(
titlePanel(h2(strong("Analysis of the composition and structure of residents"),
align = "center")),
fileInput(
inputId="fileInput",
label="Choose file",
multiple = FALSE,
accept = ".csv",
width = '100%',
buttonLabel = "Choosing ...",
placeholder = "No files selected yet"
),
sidebarPanel(
checkboxGroupInput(inputId="gender", label = "Choosing a gender feature:",
choices = c("Men" = "m",
"Women" = "f"),
selected= c("Men" = "m",
"Women" = "f")),
sliderInput(inputId = "age", label = "Indicate the age group:",
min = 1, max = 100, value = c(1, 100)),
selectInput(
inputId = "group",
label="Indicate the entrance",
choices=c(1:4),
selected = c(1:4),
multiple = TRUE,
selectize = TRUE,
width = NULL,
size = NULL
)
),
mainPanel(
navbarPage("",
tabPanel("Сommon data",
textOutput(outputId = "text1"),
),
tabPanel("Results table",
dataTableOutput(outputId = "content")
),
tabPanel("Graphic data")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
fileinfor <- reactiveValues(file=NULL,
ext=NULL,
datapath=NULL)
output$content <- renderDataTable({
fileinfor$file <- input$fileInput
fileinfor$datapath<-fileinfor$file$datapath
fileinfor.datapath <- fileinfor$file$datapath
fileinfor$ext <- tools::file_ext(fileinfor$datapath)
req(fileinfor$file)
validate(need(fileinfor$ext== "csv", "Please upload a csv file"))
fread(fileinfor$datapath,
showProgress = FALSE,
sep=";", quote="",header=TRUE)
})
output$text1 <- renderUI(renderText({
paste("Check ", fileinfor$datapath)
}))
}
# Run the application
shinyApp(ui = ui, server = server)
在服务器端,我有几个问题:
如何正确获取数据,以便您可以基于它创建一个变量并多次使用它。在我的代码示例中,您可以看到下面的服务器端代码块不再看到创建的变量:
输出 $ text1 <- renderUI (renderText ({
粘贴(“检查”,文件信息$数据路径)
}))
能否通过我的例子说明操纵变量的创建及其应用?不知道移动到哪里以及如何移动?
也许您正在寻找这个。
server <- function(input, output) {
mydf <- reactive({
req(input$fileInput)
inData <- input$fileInput
if (is.null(inData)){ return(NULL) }
mydata <- read.csv(inData$datapath, header = TRUE, sep=",")
})
output$content <- renderDT(mydf())
output$text1 <- renderText({
req(input$fileInput)
paste("Check ", input$fileInput$datapath)
})
}
首先感谢@YBS的教导。
多亏了这些小技巧,我成功解决了一半的问题。
解决方案的本质在于Shainiy如何处理变量。事实上,没有办法像编写常规代码时那样存储变量。但是,您可以编写一个反应函数,该函数将接收数据并在调用时将其发送到另一个函数框架内的变量。
需要注意的是,在教程“Mastering Shiny”
中明确提到了这种方法
因此,获得了一个版本的工作代码。
如果你想尝试最终结果,那么依次进行以下步骤:
为我们的实验创建一个 CSV 文件:
df<-data.frame(num = c(1:250),
app_num = 样本(1:100, 250, replace=T),
入口=样本(1:4, 250, replace=T),
性别=样本(c('m','f'),250,替换=T),
年龄=样本(1:100, 250, replace=T))
保存为"*csv"格式,使用命令:
write.csv2(data_file,file = file.choose(new = T), row.names = FALSE, quote = FALSE)
使用下面提到的代码创建 Shiny 应用程序:
library("shiny")
library("stringr")
library("data.table")
library("readr")
library("DT")
library("readr")
library("here")
library("ggplot2")
library("dplyr")
library("tidyr")
# Define UI for application that draws a histogram
ui <- fluidPage(
titlePanel(h2(strong("Analysis of the composition and structure of residents"),
align = "center")),
fileInput(
inputId="fileInput",
label="Choose file",
multiple = FALSE,
accept = ".csv",
width = '100%',
buttonLabel = "Choosing ...",
placeholder = "No files selected yet"
),
sidebarPanel(
checkboxGroupInput(inputId="gender", label = "Choosing a gender feature:",
choices = c("Men" = "M",
"Women" = "F"),
selected= c("Men" = "M",
"Women" = "F")),
sliderInput(inputId = "age", label = "Indicate the age group:",
min = 1, max = 100, value = c(1, 100)),
selectInput(
inputId = "group",
label="Indicate the entrance",
choices=c(1:4),
selected = c(1:4),
multiple = TRUE,
selectize = TRUE,
width = NULL,
size = NULL
)
),
mainPanel(
navbarPage("",
tabPanel("РЎommon data",
textOutput(outputId = "text1")
),
tabPanel("Results table",
dataTableOutput(outputId = "content")
),
tabPanel("Graphic data",
plotOutput(outputId = "my_plot")
)
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
fileinfor <- reactiveValues(file=NULL,
ext=NULL,
datapath=NULL)
gender = reactive({
gender <- input$gender
gender
})
age = reactive({
cbind(input$age[1],input$age[2])
})
group = reactive({
input$group
})
import_data <- reactive({
req(input$fileInput)
fileinfor$file <- input$fileInput
if (is.null(input$fileInput)){ return(NULL) }
fileinfor$datapath<-fileinfor$file$datapath
fileinfor$ext <- tools::file_ext(fileinfor$datapath)
validate(need(fileinfor$ext== "csv", "Please upload a csv file"))
import_data <- fread(fileinfor$datapath,
showProgress = FALSE,
sep=";", quote="",header=TRUE)
})
output$content <- renderDT({
GENDER = gender()
GROUP = group()
AGE = age()
req(import_data())
data_file <- import_data()
names(data_file) <- c("ID", "App", "Entrance", "Gender", "Age")
data_file <- mutate_at(data_file, vars(Gender), as.factor)
data_file<- mutate(data_file, Gender = factor(Gender, labels = c("F", "M")))
data_file <- subset(data_file,data_file$Age>=AGE[1]
& data_file$Age<=AGE[2]
& data_file$Entrance %in% GROUP
& data_file$Gender %in% GENDER)
})
output$text1 <- renderText({
req(input$fileInput)
gender <- gender()
paste(length(gender))
})
output$my_plot= reactivePlot(function(){
GENDER = gender()
GROUP = group()
AGE = age()
req(import_data())
data_file <- import_data()
names(data_file) <- c("ID", "App", "Entrance", "Gender", "Age")
data_file <- mutate_at(data_file, vars(Gender), as.factor)
data_file<- mutate(data_file, Gender = factor(Gender, labels = c("F", "M")))
data_file <- subset(data_file,data_file$Age>=AGE[1]
& data_file$Age<=AGE[2]
& data_file$Entrance %in% GROUP
& data_file$Gender %in% GENDER)
df <- group_by(data_file, data_file$Entrance, data_file$Gender)
df <- summarise(df, N = n())
names(df) <- c("Entrance", "Gender", "Quantity")
df <- mutate_at(df, vars(Gender), as.factor)
print(data_file$Gender)
#df <- mutate(df, Gender = factor(Gender, levels = c("f", "m")))
df <- complete(df, Gender, fill = list(M = 0, F = 0))
baseR.sbst.rssgn <- function(x) {
x[is.na(x)] <- 0
x
}
df$Quantity <- baseR.sbst.rssgn(df$Quantity)
ggplot(data = df, aes(x = factor(df$Gender), y = df$Quantity, fill = df$Gender)) +
geom_bar(stat = "identity", position = position_dodge2(0.9)) +
geom_text(data = df, aes(label = df$Quantity, y = 0), vjust = -0.5, position = position_dodge2(0.9)) +
scale_fill_discrete(name = "Title", labels = c("F", "M")) +
facet_wrap(~ df$Entrance, nrow = 1, strip.position = "bottom") +
xlab("Distribution of residents by entrances, taking into account gender") +
ylab("Number of residents") +
theme(
strip.placement = "outside",
strip.background = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank()
)
#?(ZMlength ~ Month, data = dat[dat$Lake == LAKE, ],
# main = "", xlab = "Month", ylab = "Shell length (mm)")
})
}
# Run the application
shinyApp(ui = ui, server = server)
有什么问题我没有解决:
- 我想在打开文件时立即计算“年龄”列中的最大值和最小值,并更改 sliderInput 的设置。我想对 selectInput 做同样的事情。
- 我想用赛尼应用程序不仅可以分析下载的数据,还可以补充CSV文件。这部分,我什么都不懂
同志们!问候。 请帮帮我...有一些重大的误解。
假设我这样创建 data.frame:
df<-data.frame(num = c(1:250),
app_num = sample(1:100, 250, replace=T),
entrance=sample(1:4, 250, replace=T),
gender=sample(c('m','f'), 250,replace=T),
age= sample(1:100, 250, replace=T))
我将其保存为“*csv”格式,使用命令:
write.csv2(data_file,file = file.choose(new = T), row.names = FALSE, quote = FALSE)
O.K。 现在我想创建一个闪亮的应用程序来显示和使用他的数据:
library("shiny")
#to work with extra string functions
library("stringr")
library("data.table")
library("readr")
# Define UI for application that draws a histogram
ui <- fluidPage(
titlePanel(h2(strong("Analysis of the composition and structure of residents"),
align = "center")),
fileInput(
inputId="fileInput",
label="Choose file",
multiple = FALSE,
accept = ".csv",
width = '100%',
buttonLabel = "Choosing ...",
placeholder = "No files selected yet"
),
sidebarPanel(
checkboxGroupInput(inputId="gender", label = "Choosing a gender feature:",
choices = c("Men" = "m",
"Women" = "f"),
selected= c("Men" = "m",
"Women" = "f")),
sliderInput(inputId = "age", label = "Indicate the age group:",
min = 1, max = 100, value = c(1, 100)),
selectInput(
inputId = "group",
label="Indicate the entrance",
choices=c(1:4),
selected = c(1:4),
multiple = TRUE,
selectize = TRUE,
width = NULL,
size = NULL
)
),
mainPanel(
navbarPage("",
tabPanel("Сommon data",
textOutput(outputId = "text1"),
),
tabPanel("Results table",
dataTableOutput(outputId = "content")
),
tabPanel("Graphic data")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
fileinfor <- reactiveValues(file=NULL,
ext=NULL,
datapath=NULL)
output$content <- renderDataTable({
fileinfor$file <- input$fileInput
fileinfor$datapath<-fileinfor$file$datapath
fileinfor.datapath <- fileinfor$file$datapath
fileinfor$ext <- tools::file_ext(fileinfor$datapath)
req(fileinfor$file)
validate(need(fileinfor$ext== "csv", "Please upload a csv file"))
fread(fileinfor$datapath,
showProgress = FALSE,
sep=";", quote="",header=TRUE)
})
output$text1 <- renderUI(renderText({
paste("Check ", fileinfor$datapath)
}))
}
# Run the application
shinyApp(ui = ui, server = server)
在服务器端,我有几个问题:
如何正确获取数据,以便您可以基于它创建一个变量并多次使用它。在我的代码示例中,您可以看到下面的服务器端代码块不再看到创建的变量:
输出 $ text1 <- renderUI (renderText ({ 粘贴(“检查”,文件信息$数据路径) }))
能否通过我的例子说明操纵变量的创建及其应用?不知道移动到哪里以及如何移动?
也许您正在寻找这个。
server <- function(input, output) {
mydf <- reactive({
req(input$fileInput)
inData <- input$fileInput
if (is.null(inData)){ return(NULL) }
mydata <- read.csv(inData$datapath, header = TRUE, sep=",")
})
output$content <- renderDT(mydf())
output$text1 <- renderText({
req(input$fileInput)
paste("Check ", input$fileInput$datapath)
})
}
首先感谢@YBS的教导。 多亏了这些小技巧,我成功解决了一半的问题。
解决方案的本质在于Shainiy如何处理变量。事实上,没有办法像编写常规代码时那样存储变量。但是,您可以编写一个反应函数,该函数将接收数据并在调用时将其发送到另一个函数框架内的变量。
需要注意的是,在教程“Mastering Shiny”
中明确提到了这种方法因此,获得了一个版本的工作代码。 如果你想尝试最终结果,那么依次进行以下步骤:
为我们的实验创建一个 CSV 文件:
df<-data.frame(num = c(1:250), app_num = 样本(1:100, 250, replace=T), 入口=样本(1:4, 250, replace=T), 性别=样本(c('m','f'),250,替换=T), 年龄=样本(1:100, 250, replace=T))
保存为"*csv"格式,使用命令:
write.csv2(data_file,file = file.choose(new = T), row.names = FALSE, quote = FALSE)
使用下面提到的代码创建 Shiny 应用程序:
library("shiny") library("stringr") library("data.table") library("readr") library("DT") library("readr") library("here") library("ggplot2") library("dplyr") library("tidyr") # Define UI for application that draws a histogram ui <- fluidPage( titlePanel(h2(strong("Analysis of the composition and structure of residents"), align = "center")), fileInput( inputId="fileInput", label="Choose file", multiple = FALSE, accept = ".csv", width = '100%', buttonLabel = "Choosing ...", placeholder = "No files selected yet" ), sidebarPanel( checkboxGroupInput(inputId="gender", label = "Choosing a gender feature:", choices = c("Men" = "M", "Women" = "F"), selected= c("Men" = "M", "Women" = "F")), sliderInput(inputId = "age", label = "Indicate the age group:", min = 1, max = 100, value = c(1, 100)), selectInput( inputId = "group", label="Indicate the entrance", choices=c(1:4), selected = c(1:4), multiple = TRUE, selectize = TRUE, width = NULL, size = NULL ) ), mainPanel( navbarPage("", tabPanel("РЎommon data", textOutput(outputId = "text1") ), tabPanel("Results table", dataTableOutput(outputId = "content") ), tabPanel("Graphic data", plotOutput(outputId = "my_plot") ) ) ) ) # Define server logic required to draw a histogram server <- function(input, output) { fileinfor <- reactiveValues(file=NULL, ext=NULL, datapath=NULL) gender = reactive({ gender <- input$gender gender }) age = reactive({ cbind(input$age[1],input$age[2]) }) group = reactive({ input$group }) import_data <- reactive({ req(input$fileInput) fileinfor$file <- input$fileInput if (is.null(input$fileInput)){ return(NULL) } fileinfor$datapath<-fileinfor$file$datapath fileinfor$ext <- tools::file_ext(fileinfor$datapath) validate(need(fileinfor$ext== "csv", "Please upload a csv file")) import_data <- fread(fileinfor$datapath, showProgress = FALSE, sep=";", quote="",header=TRUE) }) output$content <- renderDT({ GENDER = gender() GROUP = group() AGE = age() req(import_data()) data_file <- import_data() names(data_file) <- c("ID", "App", "Entrance", "Gender", "Age") data_file <- mutate_at(data_file, vars(Gender), as.factor) data_file<- mutate(data_file, Gender = factor(Gender, labels = c("F", "M"))) data_file <- subset(data_file,data_file$Age>=AGE[1] & data_file$Age<=AGE[2] & data_file$Entrance %in% GROUP & data_file$Gender %in% GENDER) }) output$text1 <- renderText({ req(input$fileInput) gender <- gender() paste(length(gender)) }) output$my_plot= reactivePlot(function(){ GENDER = gender() GROUP = group() AGE = age() req(import_data()) data_file <- import_data() names(data_file) <- c("ID", "App", "Entrance", "Gender", "Age") data_file <- mutate_at(data_file, vars(Gender), as.factor) data_file<- mutate(data_file, Gender = factor(Gender, labels = c("F", "M"))) data_file <- subset(data_file,data_file$Age>=AGE[1] & data_file$Age<=AGE[2] & data_file$Entrance %in% GROUP & data_file$Gender %in% GENDER) df <- group_by(data_file, data_file$Entrance, data_file$Gender) df <- summarise(df, N = n()) names(df) <- c("Entrance", "Gender", "Quantity") df <- mutate_at(df, vars(Gender), as.factor) print(data_file$Gender) #df <- mutate(df, Gender = factor(Gender, levels = c("f", "m"))) df <- complete(df, Gender, fill = list(M = 0, F = 0)) baseR.sbst.rssgn <- function(x) { x[is.na(x)] <- 0 x } df$Quantity <- baseR.sbst.rssgn(df$Quantity) ggplot(data = df, aes(x = factor(df$Gender), y = df$Quantity, fill = df$Gender)) + geom_bar(stat = "identity", position = position_dodge2(0.9)) + geom_text(data = df, aes(label = df$Quantity, y = 0), vjust = -0.5, position = position_dodge2(0.9)) + scale_fill_discrete(name = "Title", labels = c("F", "M")) + facet_wrap(~ df$Entrance, nrow = 1, strip.position = "bottom") + xlab("Distribution of residents by entrances, taking into account gender") + ylab("Number of residents") + theme( strip.placement = "outside", strip.background = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank() ) #?(ZMlength ~ Month, data = dat[dat$Lake == LAKE, ], # main = "", xlab = "Month", ylab = "Shell length (mm)") }) } # Run the application shinyApp(ui = ui, server = server)
有什么问题我没有解决:
- 我想在打开文件时立即计算“年龄”列中的最大值和最小值,并更改 sliderInput 的设置。我想对 selectInput 做同样的事情。
- 我想用赛尼应用程序不仅可以分析下载的数据,还可以补充CSV文件。这部分,我什么都不懂