R/ R Shiny: $ operator is invalid for atomic vectors

Viewed 237

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.

1 Answers

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")])))
Related