2

Every time I load a .xlsx file using read_excel and pass it into a data frame (let's say named data), the column headers get "." inserted in them. For example for a .xlsx file having three columns "fruit 1", "fruit 2", "fruit 3" would become "fruit.1.", "fruit.2.", "fruit.3.". In order to remove this I would use the following code -

colnames(data) <- trimws(gsub("."," ",colnames(data), fixed = TRUE))

But using the same approach in a Shiny app where I upload the .xlsx file using a fileInput button, I am not being able to use these columns. Example -

fruits <- reactive({
  req(input$file)
  inFile <- input$file
  if(is.null(inFile))
    return(NULL)

  fruits<-read_excel(paste(inFile$datapath, ".xlsx", sep=""), sheet = 1)
  
})

data <- reactive({
  req(fruits())
  data<-data.frame(fruits())
  data<- data[2:nrow(data),]
  colnames(data) <- trimws(gsub("."," ",colnames(data), fixed = TRUE))
})

if(any(is.na(data()[data()$"fruit 1" ==unique(data()$"fruit 1")[1],c("fruit 2","fruit 3")]))){
  print("There are blank fruit 2/fruit 3 names")
}else{
  print("There are no blank fruit 2/fruit 3 for the first batch")

}

The error I get is Warning: Error in $: $ operator is invalid for atomic vectors for the if line. Can someone please tell me where I am going wrong.

Phil
  • 7,287
  • 3
  • 36
  • 66
Nil_07
  • 106
  • 1
  • 8
  • 1
    You can use `data()[["fruit 1"]]`. In addition you should `return(data)` in the `reactive` i.e. `colnames(data) <- trimws(gsub("."," ",colnames(data), fixed = TRUE)); data})` – akrun Jun 02 '21 at 19:42
  • This solved my problem! Can you tell what [[]] does? I am still using $ but have returned data which solved it. – Nil_07 Jun 02 '21 at 19:56
  • Can you help me solve this [question](https://stackoverflow.com/questions/67820333/r-r-shiny-downloading-data-tables-using-download-handler)? – Nil_07 Jun 03 '21 at 11:12
  • It seems to be already answered. thanks for the link though – akrun Jun 03 '21 at 16:31
  • Thank you for taking notice. A few points are still left unanswered if you want to take a look! – Nil_07 Jun 03 '21 at 17:24
  • 1
    Can you please let the answerer know those details. I know that he is specialized in answering shiny questions – akrun Jun 03 '21 at 17:25

1 Answers1

1

The issue seems to be related to the return from the reactive block as we are not returning the original data. The last expression is assignment to column names.

data <- reactive({
  req(fruits())
  data<-data.frame(fruits())
  data<- data[2:nrow(data),]
  colnames(data) <- trimws(gsub("."," ",colnames(data), fixed = TRUE))
  data
})

Regarding other cases, it may be better to use [[ for subsetting instead of $ as $ is not general i.e. we cannot pass an object to subset

tmp <- data()[["fruit 1"]]
if(any(is.na(data()[ tmp==unique(tmp)[1],c("fruit 2","fruit 3")])))
akrun
  • 874,273
  • 37
  • 540
  • 662