Индекс вне границ
Я пытаюсь отформатировать выходной файл из моделирования Vissim в CSV-файл. Итак, у меня есть 2 Fileinputs:
- FileInput 1 предназначен для форматирования файла FZP в файл CSV, он может быть загружен в несколько файлов, но сейчас он может загружать только максимум 2, но позже я бы хотел, чтобы FileInput 1 мог обрабатывать более 2 файлов.
- FileInput 2 предназначен для объединения файла CSV после преобразования файла FZP, потому что 1 прогон моделирования VISSIM может состоять из нескольких файлов FZP, поэтому, если я хочу объединить 2 прогона или более, я бы хотел использовать FileInput 2 для его объединения.
И моя проблема в FileInput 1, потому что когда я загружаю 2 файла FZP, это не вызывает ошибку, но когда я загружаю только 1 файл FZP, это вызывает ошибку "Subscript Out of Bound", даже если я уже сделал условие, когда FileInput 1 в индексе 2 равно Null, затем создайте новый фрейм данных. Потому что я пытаюсь получить доступ к отдельному файлу из нескольких загруженных файлов для вычисления среднего значения атрибутов в файле FZP по атрибуту, называемому "VEHTYPE".
Итак, как бы я решить это?
#UI
library(shiny)
library(data.table)
shinyUI(fluidPage(
titlePanel("File Input"),
sidebarLayout(
sidebarPanel(
tags$hr(),
fileInput("file1",
"Choose FZP files",
multiple = TRUE),
fileInput("file2",
label="Upload multiple CSVs here",
multiple = TRUE),
uiOutput("column_1"),
downloadButton("download", "Filter Table"),
downloadButton("download1", "Aggregate Table")
),
mainPanel(
uiOutput("tb")
))
))
#Server
library(shiny)
library(dplyr)
library(plyr)
library(data.table)
shinyServer(function(input, output) {
data1 <- reactive({
inFile <- input$file1
if (is.null(inFile)) {
return(NULL)
} else {
inFile %>%
rowwise() %>%
do({
df <- fread(input$file1[[1, 'datapath]]', skip="t;", sep = ";", header=T, stringsAsFactor = F)
})
}
})
data2 <- reactive({
inFile <- input$file1
if (is.null(input$file1[[2, "datapath"]])) {
subData <- data1()
df <- subData[0,]
df
#data1()
} else {
inFile %>%
rowwise() %>%
do({
df <- fread(input$file1[[2, 'datapath']], skip="t;", sep = ";", header=T, stringsAsFactor = F)
})
}
})
output$column_1 <- renderUI({
if (is.null(data1())) {
return(NULL)
} else {
selectInput("column1", "Feature selection:", names(data1()))
}
})
average1 <- reactive({
#Processing data1
subsetData1 <- data1()
calAvg1 <- subsetData1[, c("VEHTYPE",input$column1)]
calAvg1 <- aggregate(calAvg1[, ncol(calAvg1)], list(VEHTYPE = calAvg1$VEHTYPE), mean)
total <- sum(calAvg1[, ncol(calAvg1)])/length(calAvg1$VEHTYPE)
dfTotal1 <- data.frame("Total", total)
names(dfTotal1) <- c("VEHTYPE", input$column1)
newDF1 <- rbind(calAvg1, dfTotal1)
})
average2 <- reactive({
#Processing data2
subsetData2 <- data2()
if(is.data.frame(subsetData2) && nrow(subsetData2)==0){
subsetData2
}else{
calAvg2 <- subsetData2[, c("VEHTYPE",input$column1)]
calAvg2 <- aggregate(calAvg2[, ncol(calAvg2)], list(VEHTYPE = calAvg2$VEHTYPE), mean)
total <- sum(calAvg2[, ncol(calAvg2)])/length(calAvg2$VEHTYPE)
dfTotal2 <- data.frame("Total", total)
names(dfTotal2) <- c("VEHTYPE", input$column1)
newDF2 <- rbind(calAvg2, dfTotal2)
}
})
finalDF <- reactive({
if(is.data.frame(average2()) && nrow(average2())==0){
average1()
}else{
final <- rbind(average1(), average2())
#average2()
}
#Merge all dataframe
#finalDF <- rbind(average1(), average2())
})
data3 <- reactive({
req(input$file2) ## ?req # require that the input is available
multiFile <- input$file2
df <- rbindlist(lapply(multiFile$datapath, fread),
use.names = TRUE, fill = TRUE)
as.data.frame(df)
return(df)
})
output$original <- renderDataTable({
data1()
})
output$filterData <- renderTable({
finalDF()
})
output$multiData <- renderTable({
data3()
})
output$download <- downloadHandler(
filename = function(){
paste("data-", Sys.Date(), ".csv", sep = "")
},
content = function(file){
write.csv(get_table(), file,row.names = F)
}
)
output$download1 <- downloadHandler(
filename = function(){
paste("data-", Sys.Date(), ".csv", sep = "")
},
content = function(file){
write.csv(data3(), file,row.names = F)
}
)
output$tb <- renderUI({
tabsetPanel(tabPanel("Original Data", dataTableOutput("original")),
tabPanel("Filter Data", tableOutput("filterData")),
tabPanel("Aggregate Data", tableOutput("multiData"))
)
})
})
FZP-файлы выглядят примерно так:
$VISION
* File: Y:\03_Studentische Arbeiten\VT\IDP\Windu\Test Simulation\test1.inpx
* Comment:
* Date: 03.08.2017 09:32:43
* PTV Vissim: 9.00 [04]
*
* Table: Vehicles In Network
*
* SIMSEC: SimSec, Simulation second (Simulation time [s]) [s]
* NO: No, Number (Number of the vehicle)
* LANE\LINK\NO: Lane\Link\No, Lane\Link\Number (Unique number of the link or connector)
* LANE\INDEX: Lane\Index, Lane\Index (Unique number of the lane)
* POS: Pos, Position (Distance on the link from the beginning of the link or connector) [m]
* POSLAT: PosLat, Position (lateral) (Lateral position at the end of the time step. Value range 0 - 1: 0: at the right lane edge 0.5: middle of the lane 1: at the left lane edge)
* EMISSIONSCO2: EmissionsCO2, Emissions CO2 (Quantity of carbon monoxide [grams / sec])
* EMISSIONSNOX: EmissionsNOx, Emissions NOx (Quantity of nitrogen oxides [grams / sec])
* FUELCONSUMPTION: FuelConsumption, Fuel consumption (Fuel consumption [US liquid gallon])
* INQUEUE: InQueue, In queue (Returns if the vehicle is in queue. Queue is defined by speed and headway treshholds. (see queue definition))
* NUMSTOPS: NumStops, Number of stops (Number of stops (cumulative): all situations in which a vehicle comes to a standstill (speed = 0), except stops at PT stops and in parking lots)
* SPEED: Speed, Speed (Speed at the end of the time step) [km/h]
* VEHTYPE: VehType, Vehicle type (Select Vehicle type from the list box)
*
* SimSec; No; Lane\Link\No; Lane\Index; Pos; PosLat; EmissionsCO2; EmissionsNOx; FuelConsumption; InQueue; NumStops; Speed; VehType
*
$VEHICLE:SIMSEC;NO;LANE\LINK\NO;LANE\INDEX;POS;POSLAT;EMISSIONSCO2;EMISSIONSNOX;FUELCONSUMPTION;INQUEUE;NUMSTOPS;SPEED;VEHTYPE
0.50;1;1;1;0.80;0.50;;;;0;0;41.70;100
0.60;1;1;1;1.96;0.50;;;;0;0;41.90;100
0.70;1;1;1;3.13;0.50;;;;0;0;42.16;100
0.80;1;1;1;4.31;0.50;;;;0;0;42.50;100
0.90;1;1;1;5.49;0.50;;;;0;0;42.91;100
1.00;1;1;1;6.69;0.50;;;;0;0;43.39;100
1.10;1;1;1;7.90;0.50;;;;0;0;43.92;100
1.20;1;1;1;9.13;0.50;;;;0;0;44.44;100
1.30;1;1;1;10.37;0.50;;;;0;0;44.96;100
1.40;1;1;1;11.63;0.50;;;;0;0;45.48;100
1.50;1;1;1;12.90;0.50;;;;0;0;45.99;100
1.60;1;1;1;14.18;0.50;;;;0;0;46.49;100
1.70;1;1;1;15.48;0.50;;;;0;0;47.00;100
1.80;1;1;1;16.79;0.50;;;;0;0;47.50;100
ошибка
Warning: Error in [[: subscript out of bounds
Stack trace (innermost first):
117: [[.data.frame
116: [[
115: fread
114: overscope_eval_next
113: do.rowwise_df
112: do
111: function_list[[k]]
110: withVisible
109: freduce
108: _fseq
107: eval
106: eval
105: withVisible
104: %>%
103: <reactive:data2>
92: data2
91: <reactive:average>
80: average
79: renderTable
78: func
77: origRenderFunc
76: output$filterData
1: shiny::runApp
2 ответа
Я думаю, что проблема заключается в назначении файла фрейму данных, я немного исправил код там.
Попробуйте изменить код сервера следующим образом и дайте мне знать, работает ли он.
shinyServer(function(input, output) {
data1 <- reactive({
inFile <- input$file1
if (is.null(inFile)) {
return(NULL)
} else {
inFile %>%
rowwise() %>%
do({
df <- fread(input$file1$datapath, skip="t;", sep = ";", header=T, stringsAsFactor = F)
})
}
})
data2 <- reactive({
inFile <- input$file1
if (is.null(inFile)) {
return(NULL)
} else {
inFile %>%
rowwise() %>%
do({
df <- fread(input$file2$datapath, skip="t;", sep = ";", header=T, stringsAsFactor = F)
})
}
})
output$column_1 <- renderUI({
if (is.null(data1())) {
return(NULL)
} else {
selectInput("column1", "Feature selection:", names(data1()))
}
})
Для преобразования файлов.fzp в.txt или.csv просто используйте командную строку DOS. Вы можете перейти к своей папке и использовать следующий синтаксис:
ren *.fzp *.txt
или ren *.fzp *.csv после этого, следуйте инструкциям чтения этой страницы из папки и используйте read.csv с "skip= " для чтения ваших файлов.