Stephen Williams Stephen Williams - 1 year ago 94
R Question

Grep multiple dataframes

I have 12 dataframes (df1:df12). All of them have a column named "gene". I would like to search for a specific character string, say "GeneX", in the "gene" column in all the dataframes and print the line with the string.

Right now I'm using 12 lines of code to do this.

df1[grep("GeneX", df1$gene), ]
df2[grep("GeneX", df2$gene), ]

Is there a way to loop over all the dataframes to do this in a more efficient way?

Answer Source

We can keep the datasets in a list and check for 'GeneX' with grep on 'Gene' column, subset the rows.

lst <- lapply(mget(paste0("df", 1:12)), function(x) x[grep("GeneX", x$Gene),])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download