The code has apply() when I think you mean lapply(). It's not really possible that this statement works as-is anywhere, so I'd check for a typo.

However, I'm not sure why the code is using lapply() at all here? As @cderv mentioned, file.rename() is already vectorized:

# Setting up example files and file names
names_files <- file.path("files", paste0("old", LETTERS[1:3], ".csv"))

dir.create("files")
file.create(names_files)
#> [1] TRUE TRUE TRUE

new_path <- file.path("files", paste0("new", LETTERS[1:3], ".csv"))

# Before renaming
list.files("files")
#> [1] "oldA.csv" "oldB.csv" "oldC.csv"

file.rename(from = names_files, to = new_path)
#> [1] TRUE TRUE TRUE

# After renaming
list.files("files")
#> [1] "newA.csv" "newB.csv" "newC.csv"

Created on 2018-09-19 by the reprex package (v0.2.0).

As an aside: it's a good idea to pay attention to which R functions are already vectorized and take advantage of that. If a function can already operate on lists of values, then that means that somebody else already wrote a for loop in the guts of that function (often in C, where it will be faster) — it doesn't make sense for you to write more loops on top of that.

3 Likes

This is an reprex update of the script above called by the app. it prints the elements of each list, but it produces an error that I do not understand. Could you please run the app to see if it does the same in your environment?

Thanks

" $ operator is invalid for atomic vectors

Please enter name/s to designate combined set/s separated by comma

[1] "1.csv 3" "2.csv 3" "3.csv 3" [1] "/home/giuseppa/Development/glycoPipeApp/name1 3" "/home/giuseppa/Development/glycoPipeApp/name2 3" [3] "/home/giuseppa/Development/glycoPipeApp/name3 3"

library(stringi)
library(fs)
library(magrittr)


glyCount1 <- function(answer = NULL, fileChoice = NULL, combination = NULL, enteredValue = NULL, nameList) {

  
# Length of list
lc <- enteredValue 
choseDataFiles = TRUE
fileLength <- length(lc)

first_path <- NULL
new_path <- NULL
old_path <- NULL

file_content <- NULL
names_files <- NULL
created_file = NULL

names_files <- as.list(dir_ls(getwd(),  regexp = "^[0-9].csv"))

new_dataFns <- as.list(unlist(strsplit(as.character(nameList), ",")))



#file.rename(names_files, created_file)

existing_file <- NULL
  for(i in 1:length(lc)){
     for(j in 1:length(lc[[i]])){
        if(!is.null(lc[[i]])){
             first_path[[j]]<- paste(getwd(), "/", lc[[i]][j], sep = "")
             file_content[[j]] <- read.csv(file = first_path[[i]], header = TRUE, sep = ",")
             old_path[[j]] <- paste(getwd(), "/", i, ".csv", sep = "")
             write.table(file_content[[j]], file = old_path[[j]],  append = TRUE, col.names = FALSE)
        }
      
     }
   
  }

old_path <- gsub(" ", "", list.files(getwd(), pattern = "^[0-9].csv"))
print(paste(old_path, length(old_path)))
 for(i in 1:length(new_dataFns)){
   new_path[i] <- gsub(" ", "", paste(getwd(), "/", new_dataFns[i], sep = ""))
 }
 print(paste(new_path, length(new_path)))
}

Created on 2018-09-19 by the reprex package (v0.2.1)

This is a new reprex after adding the statement (file.rename(...)). This time I get the error that follows:
Error: 'from' and 'to' are of different lengths. The issue is that this program runs very well when I define the names of the files in the script instead of taking them through the app's input box. However, when the script is called by the app. it produces errors. It is not the first time this happens, it happens very often, that is why I am saying would you please run the app in your environment to see if you get he same results or whether it has something to do with the application.

Please enter name/s to designate combined set/s separated by comma

[1] "1.csv 3" "2.csv 3" "3.csv 3" [1] "/home/giuseppa/Development/glycoPipeApp/name1 3" "/home/giuseppa/Development/glycoPipeApp/name2 3" [3] "/home/giuseppa/Development/glycoPipeApp/name3 3"

library(stringi)
library(fs)
library(magrittr)


glyCount1 <- function(answer = NULL, fileChoice = NULL, combination = NULL, enteredValue = NULL, nameList) {

  
# Length of list
lc <- enteredValue 
choseDataFiles = TRUE
fileLength <- length(lc)

first_path <- NULL
new_path <- NULL
old_path <- NULL

file_content <- NULL
names_files <- NULL
created_file = NULL

names_files <- as.list(dir_ls(getwd(),  regexp = "^[0-9].csv"))

new_dataFns <- as.list(unlist(strsplit(as.character(nameList), ",")))



#file.rename(names_files, created_file)

existing_file <- NULL
  for(i in 1:length(lc)){
     for(j in 1:length(lc[[i]])){
        if(!is.null(lc[[i]])){
             first_path[[j]]<- paste(getwd(), "/", lc[[i]][j], sep = "")
             file_content[[j]] <- read.csv(file = first_path[[i]], header = TRUE, sep = ",")
             old_path[[j]] <- paste(getwd(), "/", i, ".csv", sep = "")
             write.table(file_content[[j]], file = old_path[[j]],  append = TRUE, col.names = FALSE)
        }
      
     }
   
  }

old_path <- gsub(" ", "", list.files(getwd(), pattern = "^[0-9].csv"))
print(paste(old_path, length(old_path)))
 for(i in 1:length(new_dataFns)){
   new_path[i] <- gsub(" ", "", paste(getwd(), "/", new_dataFns[i], sep = ""))
 }
 print(paste(new_path, length(new_path)))
 
 file.rename(from = old_path, to = new_path)
}

Created on 2018-09-19 by the reprex package (v0.2.1)

Hi,

Could you please help me to solve the problem in my last reply to jcblum? The code that you sent works fine inn the script, but not when the script is called by the application.

This is a new reprex after adding the statement (file.rename(...)). This time I get the error that follows:
Error: 'from' and 'to' are of different lengths. The issue is that this program runs very well when I define the names of the files in the script instead of taking them through the app's input box. However, when the script is called by the app. it produces errors. It is not the first time this happens, it happens very often, that is why I am saying would you please run the app in your environment to see if you get he same results or whether it has something to do with the application.

Please enter name/s to designate combined set/s separated by comma

[1] "1.csv 3" "2.csv 3" "3.csv 3" [1] "/home/giuseppa/Development/glycoPipeApp/name1 3" "/home/giuseppa/Development/glycoPipeApp/name2 3" [3] "/home/giuseppa/Development/glycoPipeApp/name3 3"

library(stringi)
library(fs)
library(magrittr)


glyCount1 <- function(answer = NULL, fileChoice = NULL, combination = NULL, enteredValue = NULL, nameList) {

  
# Length of list
lc <- enteredValue 
choseDataFiles = TRUE
fileLength <- length(lc)

first_path <- NULL
new_path <- NULL
old_path <- NULL

file_content <- NULL
names_files <- NULL
created_file = NULL

names_files <- as.list(dir_ls(getwd(),  regexp = "^[0-9].csv"))

new_dataFns <- as.list(unlist(strsplit(as.character(nameList), ",")))



#file.rename(names_files, created_file)

existing_file <- NULL
  for(i in 1:length(lc)){
     for(j in 1:length(lc[[i]])){
        if(!is.null(lc[[i]])){
             first_path[[j]]<- paste(getwd(), "/", lc[[i]][j], sep = "")
             file_content[[j]] <- read.csv(file = first_path[[i]], header = TRUE, sep = ",")
             old_path[[j]] <- paste(getwd(), "/", i, ".csv", sep = "")
             write.table(file_content[[j]], file = old_path[[j]],  append = TRUE, col.names = FALSE)
        }
      
     }
   
  }

old_path <- gsub(" ", "", list.files(getwd(), pattern = "^[0-9].csv"))
print(paste(old_path, length(old_path)))
 for(i in 1:length(new_dataFns)){
   new_path[i] <- gsub(" ", "", paste(getwd(), "/", new_dataFns[i], sep = ""))
 }
 print(paste(new_path, length(new_path)))
 
 file.rename(from = old_path, to = new_path)
}

Created on 2018-09-19 by the reprex package (v0.2.1)

It is challenging to debug shiny apps, and you need to pay very close attention to the structure of the values that are being supplied by the various input$___ elements — it’s not necessarily the same as placeholder values you put in yourself outside of shiny.

These resources are worth investing some time in studying:

It would certainly be useful to see if the same error occurs on somebody else’s system, but unfortunately your example above still isn’t quite self-contained. The first stumbling block I see: the app code is source-ing two scripts you haven’t provided (and which don’t seem relevant here).

Can you please check the example carefully to make sure it really will run elsewhere? One way to do that would be to create a new RStudio Project for a new shiny app with just this code in it and see if it runs on your system.

You might also take a look at the advice here: Shiny debugging and reprex guide

I am sorry, I do not understand what you mean by sourcing scripts that do not seem relevant here. Those are the scripts called by the application.

Your question is about a problem that seems linked to your glyCount1 function (defined in a separate script, apparently named glyCount1.R).

But the beginning of your server definition includes this:

source("Utilities/utilities.R")
source("glycoPipeFunctions/glycoPipe_fcns.R")
source("glyCount1.R")

The app code will not run on anybody else’s system with those first two lines in it. I suggested those scripts weren’t relevant because I can’t tell if your example app is even using whatever functions are defined in them. If it is, it needs to be simplified to focus just on the thing you are having trouble with, which in this case is glyCount1.

I see. Thank you, I have removed the unnecessary statements and added one statement to the script. Could you please test these reprexes. I have copy pasted the app to a new file and it does produce the same error. Meanwhile, I will take a look at the resources you sent.

APP

library(shiny)
library(shinyjs)
#> 
#> Attaching package: 'shinyjs'
#> The following object is masked from 'package:shiny':
#> 
#>     runExample
#> The following objects are masked from 'package:methods':
#> 
#>     removeClass, show
library(fs)
library(magrittr)

ui <- fluidPage(
  selectInput("combinefiles", label = h5(strong("Do you wish to combine any data files, and compare the combined data sets? (Y/N) ")),
              choices = c("", "Y", "N"),selected = NULL),
  verbatimTextOutput("combiningFiles"),
  verbatimTextOutput("combineChosen"),
  #verbatimTextOutput("filesToCombine"),
  useShinyjs(),
  conditionalPanel(
    condition = "output.toCombine > '0'",
    selectInput(inputId = "select",label = h5(strong("Please select from the list")), choices = c(Chose = "", list.files("~/Development/glycoPipeApp")), multiple = TRUE, selectize = TRUE)
  ),
  conditionalPanel(
    condition = "output.displayAddButton > '0'",
    actionButton('add','Add')
  ),
  verbatimTextOutput("samelist"),
  conditionalPanel(
    condition = "output.displayAddButton == 1",
    actionButton("sBtn", "Press the save button to end")
  ),
  
  conditionalPanel(
    condition = "output.displayTheSaveButton  > '0'",
    textInput("textbox", h5(strong("Please enter name/s to designate combined set/s separated by comma")))),
  strong(verbatimTextOutput("list")),
  verbatimTextOutput("caption")
  
  
)

#selections = NULL,

glycoPipe <- function(response = NULL, fOfData = NULL, combineResult = NULL, listContents = NULL, vals = NULL){
  
  enteredValue = NULL
  nameList = NULL
  answer = NULL
  fileChoice = NULL
  combination = NULL
  combinations = NULL
  comb = NULL
  nameListSize = NULL
  choseDataFiles = NULL
  
  if(!is.null(response)){
    answer = response
  }
  if(!is.null(fOfData)){
    fileChoice = fOfData
  }
  
  if(!is.null(combineResult)){
    combination = combineResult
  }
  
  if(!is.null(listContents)){
    enteredValue = listContents
  }
  
  if(!is.null(vals)){
    nameList <- vals
  }
  
  glyCount1(answer, fileChoice, combination, enteredValue, nameList)
  
}

server <- function(input, output, session){
  source("glyCount1.R")
  
  listContents = NULL
  
  output$toCombine <- reactive({
    req(input$combinefiles)
    return(length(input$combinefiles))
  })
  
  outputOptions(output, "toCombine", suspendWhenHidden = FALSE)
  
  output$displayAddButton <- reactive({
    req(input$combinefiles)
    return(length(input$combinefiles))
  })
  
  outputOptions(output, "displayAddButton", suspendWhenHidden = FALSE)
  
  output$displayTheSaveButton <- reactive({
    req(input$sBtn)
    return(input$sBtn)
  })
  
  outputOptions(output, "displayTheSaveButton", suspendWhenHidden = FALSE)
  
  myValues <- reactiveValues()
  observe({
    if(input$add > 0){
      myValues$dList <- c(isolate(myValues$dList), isolate(list(input$select)))
    }
  })
  
  # #unlist(input$filescombine)
  output$samelist<-renderPrint({
    #listContents  <- list()
    
    listContents <- append(listContents, myValues$dList)
    print(listContents)
    if(input$sBtn > 0){
      numberOfSelectedSets <- glycoPipe(response = NULL, fOfData = NULL, combineResult = NULL , listContents)
      paste("Please enter", numberOfSelectedSets$nameListSize, "names to designate your", numberOfSelectedSets$nameListSize, "sets")
    }
  })
  
  
  VALUES <- list()
  observe({
    isolate({
      req(input$textbox)
      VALUES <- input$textbox
      VALUES <- append(VALUES, list(input$textbox))
      updateTextInput(session, inputId = "textbox", value = VALUES)
      
    })
  })
  
  output$caption <- renderPrint({
    vals <- list()
    vals <- append(vals, input$textbox)
    if(input$sBtn > 0){
      result <- glycoPipe(response = NULL, fOfData = NULL, combineResult = NULL, listContents = NULL, vals)
      #unlist(input$filescombine)
    }
  })
  
  session$allowReconnect(TRUE)
  
}



shinyApp(ui = ui, server = server)

Shiny applications not supported in static R Markdown documents

Created on 2018-09-19 by the reprex package (v0.2.1)

SCRIPT

library(stringi)
library(fs)
library(magrittr)


glyCount1 <- function(answer = NULL, fileChoice = NULL, combination = NULL, enteredValue = NULL, nameList) {

  
# Length of list
lc <- enteredValue 
choseDataFiles = TRUE
fileLength <- length(lc)

first_path <- NULL
new_path <- NULL
old_path <- NULL

file_content <- NULL
names_files <- NULL
created_file = NULL

names_files <- as.list(dir_ls(getwd(),  regexp = "^[0-9].csv"))

new_dataFns <- as.list(unlist(strsplit(as.character(nameList), ",")))



#file.rename(names_files, created_file)

existing_file <- NULL
  for(i in 1:length(lc)){
     for(j in 1:length(lc[[i]])){
        if(!is.null(lc[[i]])){
             first_path[[j]]<- paste(getwd(), "/", lc[[i]][j], sep = "")
             file_content[[j]] <- read.csv(file = first_path[[i]], header = TRUE, sep = ",")
             old_path[[j]] <- paste(getwd(), "/", i, ".csv", sep = "")
             write.table(file_content[[j]], file = old_path[[j]],  append = TRUE, col.names = FALSE)
        }
      
     }
   
  }

old_path <- gsub(" ", "", list.files(getwd(), pattern = "^[0-9].csv"))
print(paste(old_path, length(old_path)))
 for(i in 1:length(new_dataFns)){
   new_path[i] <- gsub(" ", "", paste(getwd(), "/", new_dataFns[i], sep = ""))
 }
 print(paste(new_path, length(new_path)))
 
 file.rename(from = old_path, to = new_path)
}

Hi,

Could you please run this application and the scrip and tell me if you find the same error on your environment? I am sending the reprex for the app, the script and to make the files.

APP


library(shiny)
library(shinyjs)
#> 
#> Attaching package: 'shinyjs'
#> The following object is masked from 'package:shiny':
#> 
#>     runExample
#> The following objects are masked from 'package:methods':
#> 
#>     removeClass, show
library(fs)
library(magrittr)


ui <- fluidPage(
  selectInput("combinefiles", label = h5(strong("Do you wish to combine any data files, and compare the combined data sets? (Y/N) ")),
              choices = c("", "Y", "N"),selected = NULL),
  verbatimTextOutput("combiningFiles"),
  verbatimTextOutput("combineChosen"),
  #verbatimTextOutput("filesToCombine"),
  useShinyjs(),
  conditionalPanel(
    condition = "output.toCombine > '0'",
    selectInput(inputId = "select",label = h5(strong("Please select from the list")), choices = c(Chose = "", list.files("~/Development/glycoPipeApp")), multiple = TRUE, selectize = TRUE)
  ),
  conditionalPanel(
    condition = "output.displayAddButton > '0'",
    actionButton('add','Add')
  ),
  verbatimTextOutput("samelist"),
  conditionalPanel(
    condition = "output.displayAddButton == 1",
    actionButton("sBtn", "Press the save button to end")
  ),
  
  conditionalPanel(
    condition = "output.displayTheSaveButton  > '0'",
    textInput("textbox", h5(strong("Please enter name/s to designate combined set/s separated by comma")))),
  strong(verbatimTextOutput("list")),
  verbatimTextOutput("caption")
  
  
)

#selections = NULL,

glycoPipe <- function(response = NULL, fOfData = NULL, combineResult = NULL, listContents = NULL, vals = NULL){
  
  enteredValue = NULL
  nameList = NULL
  answer = NULL
  fileChoice = NULL
  combination = NULL
  combinations = NULL
  comb = NULL
  nameListSize = NULL
  choseDataFiles = NULL
  
  if(!is.null(response)){
    answer = response
  }
  if(!is.null(fOfData)){
    fileChoice = fOfData
  }
  
  if(!is.null(combineResult)){
    combination = combineResult
  }
  
  if(!is.null(listContents)){
    enteredValue = listContents
  }
  
  if(!is.null(vals)){
    nameList <- vals
  }
  
  glyCount1(answer, fileChoice, combination, enteredValue, nameList)
  
}

server <- function(input, output, session){
  source("glyCount1.R")
  
  listContents = NULL
  
  output$toCombine <- reactive({
    req(input$combinefiles)
    return(length(input$combinefiles))
  })
  
  outputOptions(output, "toCombine", suspendWhenHidden = FALSE)
  
  output$displayAddButton <- reactive({
    req(input$combinefiles)
    return(length(input$combinefiles))
  })
  
  outputOptions(output, "displayAddButton", suspendWhenHidden = FALSE)
  
  output$displayTheSaveButton <- reactive({
    req(input$sBtn)
    return(input$sBtn)
  })
  
  outputOptions(output, "displayTheSaveButton", suspendWhenHidden = FALSE)
  
  myValues <- reactiveValues()
  observe({
    if(input$add > 0){
      myValues$dList <- c(isolate(myValues$dList), isolate(list(input$select)))
    }
  })
  
  # #unlist(input$filescombine)
  output$samelist<-renderPrint({
    #listContents  <- list()
    
    listContents <- append(listContents, myValues$dList)
    print(listContents)
    if(input$sBtn > 0){
      numberOfSelectedSets <- glycoPipe(response = NULL, fOfData = NULL, combineResult = NULL , listContents)
      paste("Please enter", numberOfSelectedSets$nameListSize, "names to designate your", numberOfSelectedSets$nameListSize, "sets")
    }
  })
  
  
  VALUES <- list()
  observe({
    isolate({
      req(input$textbox)
      VALUES <- input$textbox
      VALUES <- append(VALUES, list(input$textbox))
      updateTextInput(session, inputId = "textbox", value = VALUES)
      
    })
  })
  
  output$caption <- renderPrint({
    vals <- list()
    vals <- append(vals, input$textbox)
    if(input$sBtn > 0){
      result <- glycoPipe(response = NULL, fOfData = NULL, combineResult = NULL, listContents = NULL, vals)
      #unlist(input$filescombine)
    }
  })
  
  session$allowReconnect(TRUE)
  
}



shinyApp(ui = ui, server = server)

Shiny applications not supported in static R Markdown documents

Created on 2018-09-19 by the reprex package (v0.2.1)

SCRIPT

library(stringi)
library(fs)
library(magrittr)


glyCount1 <- function(answer = NULL, fileChoice = NULL, combination = NULL, enteredValue = NULL, nameList) {

 
lc <- enteredValue 
choseDataFiles = TRUE
fileLength <- length(lc)

first_path <- NULL
new_path <- NULL
old_path <- NULL

file_content <- NULL
names_files <- NULL
created_file = NULL

names_files <- as.list(dir_ls(getwd(),  regexp = "^[0-9].csv"))

new_dataFns <- as.list(unlist(strsplit(as.character(nameList), ",")))



#file.rename(names_files, created_file)

existing_file <- NULL
  for(i in 1:length(lc)){
     for(j in 1:length(lc[[i]])){
        if(!is.null(lc[[i]])){
             first_path[[j]]<- paste(getwd(), "/", lc[[i]][j], sep = "")
             file_content[[j]] <- read.csv(file = first_path[[i]], header = TRUE, sep = ",")
             old_path[[j]] <- paste(getwd(), "/", i, ".csv", sep = "")
             write.table(file_content[[j]], file = old_path[[j]],  append = TRUE, col.names = FALSE)
        }
      
     }
   
  }

old_path <- gsub(" ", "", list.files(getwd(), pattern = "^[0-9].csv"))
print(paste(old_path, length(old_path)))
 for(i in 1:length(new_dataFns)){
   new_path[i] <- gsub(" ", "", paste(getwd(), "/", new_dataFns[i], sep = ""))
 }
 print(paste(new_path, length(new_path)))
 
 file.rename(from = old_path, to = new_path)
}

Created on 2018-09-19 by the reprex package (v0.2.1)

CREATE FILES SCRIPT

library(magrittr)
library(reprex)

JF_160426_Dep2Plas_tryp_Gpep_SIDtargPSM<- NULL

JF_160426_Dep2Plas_tryp_Gpep_SIDtargPSM %>%        # table that should become a file
  head(5) %>%    # 5 lines might be plenty?
  dput()
#> NULL
0
#> [1] 0
JF_160426_Dep2Plas_tryp_Gpep_SIDtargPSM <-    
  # Everything below here is the output from above. I used
  #  fake data for this.
  structure(list(
    
    confidence = c("High", "High", "High", "High", "High", "High", "Medium", "High", "High", "High", "High", "High", "High", "High", "High", "Medium", "High", "High", "Medium","High"
    ),
    deltaScore = c("0.1667", "0.5789", "1", "0.56", "0.52", "1", "0.56", "0.5882", "1", "0.52", "1", "0.56", "0.5", "0.2857", "0.5556", "0.55", "0", "0.2857", "0.5789", "0.5"
    ),
    
    PSM_ambiguity = c("Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Unambiguous", "Ambiguous", "Unambiguous", "Unambiguous", "Medium"
    ),
    
    Annotated_Sequence = c("InHcR", "InHcR", "InHcR", "InHcR", "InHcR", "InHcR", "InHcR", "EnGTVSR", "InHcR", "InHcR", "InHcR",  "InHcR", "InHcR", "InHcR", "InHcR", "InHcR", "InHcR", "InHcR", "InHcR", "InHcR"
    ),
    
    Modifications = c("N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)","N2(HexNAc) C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)", "N2(HexNAc); C4(Carbamidomethyl)","N2(HexNAc); C4(Carbamidomethyl", "N2(HexNAc); C4(Carbamidomethyl", "N2(HexNAc); C4(Carbamidomethyl)"
    )
    
  ), .Names = c("confidence", "deltaScore","PMS_Ambiguity", "Annotated_Sequence", "Modifications"), row.names = c(
    NA,
    -20L
  ), class = c("tbl_df", "tbl", "data.frame"))

write.csv(JF_160426_Dep2Plas_tryp_Gpep_SIDtargPSM, "F_160426_Dep2Plas_tryp_Gpep_SIDtargPSM.csv")
rm(JF_160426_Dep2Plas_tryp_Gpep_SIDtargPSM)

Created on 2018-09-19 by the reprex package (v0.2.1)

This script works great. It produces the expected result. Why does not the same structure work when I call the script from the app?

Thanks



new_dataFns <- list("name1", "name2", "name3")
new_path <-  lapply(new_dataFns,
                     function(new_dataFns){
                       paste(getwd(), "/", new_dataFns, sep = "")
                     })

print(new_path)
#> [[1]]
#> [1] "/tmp/Rtmp45cbvl/reprex2bdc4b02a380/name1"
#> 
#> [[2]]
#> [1] "/tmp/Rtmp45cbvl/reprex2bdc4b02a380/name2"
#> 
#> [[3]]
#> [1] "/tmp/Rtmp45cbvl/reprex2bdc4b02a380/name3"

old_dataFns <- list("1.csv", "2.csv", "3.csv")

for(i in 1:length(old_dataFns)){
  old_dataFns[i] <- gsub(" ", "", paste(getwd(), "/", old_dataFns[i]))

}
print(old_dataFns)
#> [[1]]
#> [1] "/tmp/Rtmp45cbvl/reprex2bdc4b02a380/1.csv"
#> 
#> [[2]]
#> [1] "/tmp/Rtmp45cbvl/reprex2bdc4b02a380/2.csv"
#> 
#> [[3]]
#> [1] "/tmp/Rtmp45cbvl/reprex2bdc4b02a380/3.csv"

lapply(1:3, function(i){ file.rename(old_dataFns[[i]], new_path[[i]]) })
#> Warning in file.rename(old_dataFns[[i]], new_path[[i]]): cannot rename
#> file '/tmp/Rtmp45cbvl/reprex2bdc4b02a380/1.csv' to '/tmp/Rtmp45cbvl/
#> reprex2bdc4b02a380/name1', reason 'No such file or directory'
#> Warning in file.rename(old_dataFns[[i]], new_path[[i]]): cannot rename
#> file '/tmp/Rtmp45cbvl/reprex2bdc4b02a380/2.csv' to '/tmp/Rtmp45cbvl/
#> reprex2bdc4b02a380/name2', reason 'No such file or directory'
#> Warning in file.rename(old_dataFns[[i]], new_path[[i]]): cannot rename
#> file '/tmp/Rtmp45cbvl/reprex2bdc4b02a380/3.csv' to '/tmp/Rtmp45cbvl/
#> reprex2bdc4b02a380/name3', reason 'No such file or directory'
#> [[1]]
#> [1] FALSE
#> 
#> [[2]]
#> [1] FALSE
#> 
#> [[3]]
#> [1] FALSE

Created on 2018-09-19 by the reprex package (v0.2.1)

This script almost works. It renames the 3 files and the files have the right content, but instead of renaming them as name1.csv, name2.csv, name3.csv it renames them as NULL.csv, name1.csv and name2.csv
NULL.csv has the content of 1.csv, name1.csv has the content of 2.csv and name2.csv has the content of 3.csv. I get the error: Error: subscript out of bounds. Is there any reason why this should occur?

Thanks

library(stringi)
library(fs)
library(magrittr)


glyCount1 <- function(answer = NULL, fileChoice = NULL, combination = NULL, enteredValue = NULL, nameList) {

  
# Length of list
lc <- enteredValue 
choseDataFiles = TRUE
fileLength <- length(lc)

first_path <- NULL
new_path <- NULL
old_path <- NULL

file_content <- NULL
names_files <- NULL
created_file = NULL

names_files <- as.list(dir_ls(getwd(),  regexp = "^[0-9].csv"))

new_dataFns <- as.list(unlist(strsplit(as.character(nameList), ",")))



#file.rename(names_files, created_file)

existing_file <- NULL
  for(i in 1:length(lc)){
     for(j in 1:length(lc[[i]])){
        if(!is.null(lc[[i]])){
             first_path[[j]]<- paste(getwd(), "/", lc[[i]][j], sep = "")
             file_content[[j]] <- read.csv(file = first_path[[i]], header = TRUE, sep = ",")
             old_path[[j]] <- paste(getwd(), "/", i, ".csv", sep = "")
             write.table(file_content[[j]], file = old_path[[j]],  append = TRUE, col.names = FALSE)
        }
      
     }
   
  }

old_path <- gsub(" ", "", list.files(getwd(), pattern = "^[0-9].csv"))
print(paste(old_path, length(old_path)))
 for(i in 1:length(new_dataFns)){
   new_path[i] <- gsub(" ", "", paste(getwd(), "/", new_dataFns[i], sep = ""))
 }
 print(paste(new_path, length(new_path)))
 
 lapply(1:length(old_path), function(i){ file.rename(old_path[[i]], new_path[[i]]) })
 # if(!is.null(new_dataFns))
 # file.rename(from = old_path, to = new_path)
}

Created on 2018-09-19 by the reprex package (v0.2.1)

I tried to run your example app, but I'm afraid I don't understand how it's supposed to work. This doesn't seem like an example that's going to be easy for other people to run without more instructions on how to set it up and what is supposed to go into the different input fields.

Honestly, expecting helpers to do that much setup work is asking a lot — maybe consider setting up an example app with all the right sample files in all the right places as an RStudio Cloud project and sharing that, instead?

It also seems like you may need to rethink your UI for this app. Due to all the conditionalPanel() statements, I wasn't able to access the second text entry box until after clicking the "Press the save button to end" button — but glyCount1() runs when you press this button, even though there's no way to supply all the information yet.

I'm also not sure why there are so many statements in the code setting variables to NULL. I don't think they are all necessary.

Anyway, here's what happened, in case it's helpful:

When app launches

45

After choosing "Y" from selectInput

03

After entering some values

I wasn't sure what was supposed to go in this box, since there isn't actually a list to select from. I tried entering some fake file names, clicking Add each time. The verbatimOutput did not seem to be working correctly (or else the values aren't being stored correctly by the app!).
41

Just before clicking "Press the save button to end"

After clicking "Press the save button to end"

Now the second text box appears. So do some errors. I can tell from some other things I tried that glyCount1 was run once after the "Press the save button to end" button was clicked.

After trying to enter some values in the second text box

Thanks to how the reactivity works in this app, every time you enter anything into this text box glyCount1() is run. But nothing I entered seemed to change the error result.

Thank you for running the app. The reason why I sent the reprex on how to make a file is so that you could create the files. The input box lists the files stored in (getwd()) and allows the user to make multiple selections. The application is supposed to run glyCount1.R when the user presses that final button (press the button to end, no before the button is pressed. I need for this app to be designed the way it is. But, you confirm the fact that there is a problem with the input box. Thank you for your help. I will see what I can do.

Could you please tell me how to go about creating a RStudio Cloud project?

Thanks

To create a project in RStudio Cloud, you will need to sign up at rstudio.cloud. Then, in your workspace, click "New Project" - a new project will be created for you, and you'll see the familiar RStudio interface in your browser. You can then create a new shiny app in the usual way (File > New File > Shiny Web App) or port your existing app in using the "Upload" button in the Files tab.

If you have your app in a git repo, it's a bit easier - the "New Project" button will allow you to specify the URL of your repo.

Since this is for the purposes of sharing, make sure to click the "Settings" gear at the top of your workspace, choose "Access", and set the "Who can view this project" to "Everyone."

1 Like

Thanks very much for your quick response

Sorry, I should have been more clear! I did use the code provided to create files. That code only creates a single file in the working directory. The file it creates has a name that doesn't match some of the regex patterns used in the code, as far as I can tell — that might be something you want to look more closely at.

In practice, there were no options available so the selectize box behaved like a simple text entry box. Looking more closely, you still had an absolute path to somewhere on your computer in the code that creates the list of choices:

conditionalPanel(
    condition = "output.toCombine > '0'",
    selectInput(
       inputId = "select",
       label = h5(strong("Please select from the list")), 
       choices = c(Chose = "", list.files("~/Development/glycoPipeApp")), 
       multiple = TRUE, 
       selectize = TRUE
    )
  ),

As a general note, there are a few places in this app that seem to me like you're kind of programming against the grain of how shiny works. Reactivity means that you aren't writing code that says "do this first, then that, then that other thing" — you're preparing code recipes that will be run in an order that shiny decides. Adjusting to this model from a more imperative coding style can feel like turning your head inside out! If you haven't seen them already, I really recommend these videos for getting a better handle on reactivity:
https://www.rstudio.com/resources/videos/effective-reactive-programming/

yes, I forgot to tell you that the program part that names the file has to be updated to create the other two files. I have learn to do the conditional panel below at RStudio Community, and I have read about reactivity. Could you please explain why the code below does not relate to reactivity? Could you please explain your view on reactivity and why the code below does not work with reactivity? May be I am wrong.

conditionalPanel(
    condition = "output.toCombine > '0'",
    selectInput(
       inputId = "select",
       label = h5(strong("Please select from the list")), 
       choices = c(Chose = "", list.files("~/Development/glycoPipeApp")), 
       multiple = TRUE, 
       selectize = TRUE
    )
  ),

The code below works well, provided that 1.csv, 2.csv, 3.csv exists (they were created with anther program in this case for the purpose of demonstration only. And this is what I would like to accomplish. The only difference between this script and the one called by the application is that in this script "name1", "name2", and "name3" are created by me as a list in the script. However in the case of the app, those names are input by the user through the text box and are passed as a list from the app to the script. if it is not too much to ask, you could create 3 empty files in your working directory and name them 1.csv, 2.csv. 3.csv. This way you could run the program and see that the same code works in the script, but not when the script is called by the app.

Thank you

new_dataFns <- list("name1", "name2", "name3")
new_path <-  lapply(new_dataFns,
                    function(new_dataFns){
                      paste(getwd(), "/", new_dataFns, sep = "")
                    })

print(new_path)

old_dataFns <- list("1.csv", "2.csv", "3.csv")

for(i in 1:length(old_dataFns)){
 old_dataFns[i] <- gsub(" ", "", paste(getwd(), "/", old_dataFns[i]))

}
print(old_dataFns)

lapply(1:3, function(i){ file.rename(old_dataFns[[i]], new_path[[i]]) })