Search code examples
rlistfunctionsapply

How to simplify the codes of a list in one line in R?


I have a list of microarray platform text files containing of Gene Symbol accessions. I trim Gene Symbols with below codes.

p[[1]]<- data.frame(sapply(p[[1]], function(x) sub("/.*", "", x)))
p[[1]]<- data.frame(sapply(p[[1]], function(x) sub("-.*", "", x)))
p[[1]]<- data.frame(sapply(p[[1]], function(x) sub("\\..*", "", x)))
p[[1]]<- data.frame(sapply(p[[1]], function(x) sub("\\s", "", x)))
p[[2]]<- data.frame(sapply(p[[2]], function(x) sub("/.*", "", x)))
p[[2]]<- data.frame(sapply(p[[2]], function(x) sub("-.*", "", x)))
p[[2]]<- data.frame(sapply(p[[2]], function(x) sub("\\..*", "", x)))
p[[2]]<- data.frame(sapply(p[[2]], function(x) sub("\\s", "", x)))

How can I simplify these codes in two lines? Thank so much for any idea.


Solution

  • Use regex's pipe operator that equates to the logical OR:

    p[[1]] <- data.frame(sapply(p[[1]], function(x) sub("/.*|-.*|\\..*|\\s", "", x)))
    
    p[[2]] <- data.frame(sapply(p[[2]], function(x) sub("/.*|-.*|\\..*|\\s", "", x)))