Rename 3 files with a different name each

Hi,

I would like to rename 3 different files found in the same directory. The original file names are: 1.csv, 2.csv, 3.csv. I would like to remain these 3 files to name1.csv, name2.csv, name3.csv. Please see code below. I get the error; Error in file.rename(old_path, new_path) : invalid 'to' argument
Called from: file.rename(old_path, new_path). Could you please help me with this issue?

Thanks

new_dataFns <- list("name1", "name2", "name3")
new_path <-  lapply(new_dataFns,
                     function(new_dataFns){
                       paste("~/Development/glycoPipeApp/OUT/openMS/INPUT_DATA/INPUT_DATA_OUT/", new_dataFns, sep = "")
                     })

print(new_path)
#> [[1]]
#> [1] "~/Development/glycoPipeApp/OUT/openMS/INPUT_DATA/INPUT_DATA_OUT/name1"
#> 
#> [[2]]
#> [1] "~/Development/glycoPipeApp/OUT/openMS/INPUT_DATA/INPUT_DATA_OUT/name2"
#> 
#> [[3]]
#> [1] "~/Development/glycoPipeApp/OUT/openMS/INPUT_DATA/INPUT_DATA_OUT/name3"

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

old_path <- lapply(old_dataFns,
                   function(old_dataFns){
                     paste("~/Development/glycoPipeApp/OUT/openMS/INPUT_DATA/INPUT_DATA_OUT/", old_dataFns, sep = "")
                   })
print(old_dataFns)
#> [[1]]
#> [1] "1.csv"
#> 
#> [[2]]
#> [1] "2.csv"
#> 
#> [[3]]
#> [1] "3.csv"

lapply(old_path,
       function(old_path){
         file.rename(old_path, new_path)
       })
#> Error in file.rename(old_path, new_path): invalid 'to' argument

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

here you are just iterating through old_path but not new_path. new_path contains your three destination file. in file.rename, you should provide only one if you provide only one old path. Iterate over a numeric index to select the element

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

it may work if I am not missing something else.
However, I think file.rename is vectorised so this should work

file.rename(old_path, new_path)

without iteration.

Also, for this kind of task, take a look at the new fs :package:

Hello,

I am inserting a reprex of the minimal app I can get to demonstrate the problem and a reprex of the script called by the app, together with a reprext of the program that creates the files. The problem I am having is that the statement "names_files <- list.files(getwd(), pattern = "[0-9].csv", all.files = FALSE, full.names = TRUE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = TRUE)" at the end of the script called by the app returns the error "Error: $ operator is invalid for atomic vectors". However if i write that statement at the beginning of the script or inside the outermost loop, the error does not occur. Could you please run these programs and see if the same thing happens in your environment. I know this is a different question, but I cannot test the file.rename(function) is I cannot list the directory.

Thanks,

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


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){
    listContents = NULL
    
    source("Utilities/utilities.R")
    source("glycoPipeFunctions/glycoPipe_fcns.R")
    source("glyCount1.R")
    
    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)

SCRIPT CALLED BY THE APP

ibrary(stringi)


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

  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)
            
        }
     }
    
    new_dataFns <- as.list(unlist(strsplit(as.character(nameList), ",")))
    for(i in 1:length(new_dataFns)){
      new_path[i] <- gsub(" ", "", paste(getwd(), "/", new_dataFns[i], sep = ""))
    
    }
   
  }
names_files <- list.files(getwd(), pattern = "[0-9].csv", all.files = FALSE, full.names = TRUE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = TRUE)
#apply(1:length(new_path), function(i){ file.rename(names_files[[i]], new_path[[i]]) })
#file.rename(names_files, new_path)

}

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

SCRIPT TO CREATE FILES

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)

I solved the problem by adding as.list to the list.file() statement "names_files <- as.list(list.files(getwd(), pattern = "[0-9].csv", all.files = FALSE, full.names = TRUE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = TRUE))". When I run the statement "apply(1:length(names_files), function(i){ file.rename(names_files[[i]], new_path[[i]]) })" I get the error below:

"argument "FUN" is missing, with no default". However the same statement works well and produces the required results in the script I sent you before. I have notice in many occasions that some functions or just simple looping code works well when I run a script directly (not called by the application), but the same script with the same code does not wok when called by the application. I have cleaned the environment and my RStudio IDE is set up to not to unload the .RData. May be there is a command that I can use so that the environment does not get saved when I restart the application?

If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:

Hi,

But, I have not been able to solve the issue. I cannot rename the files yet.

I was mislead by this sorry. :wink:

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.