kolas0202
kolas0202

Reputation: 163

Skip/delete rows having empty cells

I am uploading reading a text file in my shiny app. Here is how I am reading it in shiny app:

data <- reactive({
    req(input$file)
    df <- read.table(file=input$file$datapath[input$file$name==input$Select], skip = 15, sep=input$sep, header = input$header, stringsAsFactors = input$stringAsFactors)
    updateSelectInput(session, inputId = 'xcol', label = 'X Variable',
                      choices = names(df), selected = names(df)[1])
    updateSelectInput(session, inputId = 'ycol', label = 'Y Variable',
                      choices = names(df), selected = names(df)[2])
    return(df)
  })

Now, I want to delete/skip the rows in the uploaded dataset having empty cells.

My attempt:

df[!apply(df == "", 1, all),]

But, it is not working.

Is there a different way to do it when using read.table?

Upvotes: 1

Views: 216

Answers (2)

kolas0202
kolas0202

Reputation: 163

I got my answer:

Here is the code: Raw Data:

data <- reactive({
    req(input$file)
    df <- read.table(file=input$file$datapath[input$file$name==input$Select], skip = 15, sep=input$sep, header = input$header, stringsAsFactors = input$stringAsFactors, skipNul = TRUE, na.strings = "")
    updateSelectInput(session, inputId = 'xcol', label = 'X Variable',
                      choices = names(df), selected = names(df)[1])
    updateSelectInput(session, inputId = 'ycol', label = 'Y Variable',
                      choices = names(df), selected = names(df)[2])
    return(df)
  })

Data with removing the rows with empty cells:

data_1 <- reactive({
    req(input$file)
    x <- data()[, c(input$xcol, input$ycol)]
    x[x == ""] <- NA
    M <- na.omit(x)
    return(M)
  })

Upvotes: 0

r2evans
r2evans

Reputation: 160407

@maydin's link works great for NA values, but you'll need a little bit more to check for a specific value (i.e, "", the empty string).

df <- data.frame(a=c('a','b',''), b="")
rowSums(df != "") == 0
# [1] FALSE FALSE  TRUE

That tells you which rows have exactly 0 non-empty strings on the row. If even one of the columns has something more than zero-length-string, then it'll pop as false.

Using this, we'll look for only rows with 1 or more non-empty-strings.

df[rowSums(df != "") > 0, ]
#   a b
# 1 a  
# 2 b  

Upvotes: 1

Related Questions