Remove NA strings from table (characters) in R

Viewed 876

How can I remove NA strings in a simple data frame like the one below, which consists of a single column, in R?

head(test)
Column1 
[1] "Gene1 Gene2 Gene3 NA NA NA NA" 
[2] "Gene41 NAGene218 GeneX NA"
[3] "Gene19 GeneNA NA NA NA NA NA"

Some genes start or end with 'NA', so to avoid getting rid of those NAs, the gsub regex has to specify the position of the NA in the string... Something like: test2 <- gsub('^ NA$', "", test$Column1), with ^ indicating that ' NA' has to be at the start and $ at the end of the string... I am sure it's something simple, but I don't understand what I am doing wrong? (As I am not very familiar with these regex symbols)

[UPDATE] - Desired output

head(test2)
Column1 
[1] "Gene1 Gene2 Gene3" 
[2] "Gene41 NAGene218 GeneX"
[3] "Gene19 GeneNA"
3 Answers

You may use

test$Column1 <- gsub("^NA(?:\\s+NA)*\\b\\s*|\\s*\\bNA(?:\\s+NA)*$", "", test$Column1)

See the regex demo

Details

  • ^NA(?:\s+NA)*\b\s* - Alternative 1:
    • ^ - start of string
    • NA - NA string
    • (?:\s+NA)* - 0 or more repetitions of 1+ whitespaces and NA text
    • \b - make sure there is a word boundary (no NAGene match should occur)
    • \s* - 0+ whitespaces
  • | - or
  • \s*\bNA(?:\s+NA)*$ - Alternative 2:
    • \s* - 0+ whitespaces
    • \b - make sure there is a word boundary (no GeneNA match should occur)
    • NA - NA string
    • (?:\s+NA)* - 0 or more repetitions of 1+ whitespaces and NA text
    • $ - end of string.

Try this from stringr:

library(tidyverse)

test <- tibble(column1 = c("Gene1 Gene2 Gene3 NA NA NA NA" ,
                           "Gene41 NAGene218 GeneX NA",
                           "Gene19 GeneNA NA NA NA NA NA"))

test %>%
 mutate(column1 = str_remove_all(column1, " NA|NA"))

Or:

library(stringr)
library(tidyverse)

x <- c("Gene1 Gene2 Gene3 NA NA NA NA", "Gene41 NAGene218 GeneX NA", "Gene19 GeneNA NA NA NA NA NA")

str_split(x, "\\s", simplify = TRUE) %>%
  as_tibble() %>%
  mutate_all(~str_remove(.x, "^(NA)|(NA)$"))

# V1     V2      V3    V4    V5    V6    V7   
# <chr>  <chr>   <chr> <chr> <chr> <chr> <chr>
#   1 Gene1  Gene2   Gene3 ""    ""    ""    ""   
# 2 Gene41 Gene218 GeneX ""    ""    ""    ""   
# 3 Gene19 Gene    ""    ""    ""    ""    ""   
Related