0
votes

I am trying to filter rows out from a dataframe and write the resulting shorter dataframe to a new file. I can get as far as getting to work on individual files, but trying to use lappy to run this process over multiple files (and giving different names to the output files) is proving troublesome.

Im trying to filter out rows based on whether the values in "aaSeqCDR3" contain "_" or "*"

so far I have:

productseq <-function(x){
#establish filter criteria
filter <- c("\\*", "_")
#Filter data set to new variable
df2 <- df[!grepl(paste(filter, collapse = "|"), df$aaSeqCDR3),]
write.delim(df2, "df2.txt", sep= " ")}

however trying to apply it to a vector containing multiple data frame names (names)

nameproduct <- lapply(names, productiveseq)

i get the error:

error in UseMethod("filter_") : no applicable method for 'filter_' applied to an object of class "character"

Im very lost at the moment, and would appreciate any insight.

An example dataframe is below:

ID  allDHitsWithScore   allJHitsWithScore   allCHitsWithScore   aaSeqCDR3
0   290 0.031402274 TGTGCCAGCGGCAGCCCCAATTCACCCCTCCACTTT    CASGSPNSPLHF
1   168 0.018191662 TGTGCTCTGAGTGATCAGAATAAGGGCAGGAGAGCACTTACTTTT   CALSDQNKGRRALTF
2   49  0.005305902 TGTGCAGTCTCCAAAGCTGCAGGCAACAAGCTAACTTTT CAVSKAAGNKLTF
3   16  0.001732539 TGCAGTGCTAGAGGGCGCTTAGCCAAAAACATTCAGTACTTC  CSARGRLAKNIQYF
4   15  0.001624256 TGTGCCTGAAGGAATGCAGGCAAATCAACCTTT   CA*RNAGKSTF
5   14  0.001515972 TGCAGTGCTAGAGTTGGACAGGGAGGGTTCTTC   CSARVGQGGFF
6   13  0.001407688 TGTGCCAGCAGTTACTTGGGACAGGGGGGAAACATTCAGTACTTC   CASSYLGQGGNIQYF
7   12  0.001299404 TGTGCCAGCAGTTTATGGGACTAGCGGGGGGTTCGAGCTCCTACAATGAGCAGTTCTTC CASSLWD*RG_SSSYNEQFF
1

1 Answers

5
votes

Because you are passing a character vector of data frame names and not data frame objects themselves, use get inside your function.

Also, do note you are writing to same file, df2.txt, so this same file will be overwritten with each iteration. To resolve, paste the x character value to text file name. And be sure to return data frame instead of NULL from write.delim call being last line of function.

productseq <- function(x) {
    # Retrieve data frame
    df <- get(x)

    # Establish filter criteria
    filter <- c("\\*", "_")

    # Filter data set to new variable
    df2 <- df[!grepl(paste(filter, collapse = "|"), df$aaSeqCDR3),]

    write.delim(df2, paste0(x, ".txt"), sep= " ")

    # Return filtered data
    return(df2)
}

# LIST OF FILTERED DATA FRAMES EACH EXPORTED TO .txt FILE
nameproduct <- lapply(names, productiveseq)