Sebastian Zeki Sebastian Zeki - 1 year ago 64
R Question

How to create custom function for list of dataframes from split

I'm new to functions and just discovered split.
I have a list of dataframes from the split function. For each dataframe I would like to count the number of a specific regular expression and dump the overall count in a vector (which I then intend to add to a matrix for all the dataframes).

Although its easy to create the counts, I don't know how to then translate this into a function that will do the same thing for all the dataframes in the list:

Here is my attempt so far

lapply(PClst, function(x)nrow(x[grepl(".*denoma.*,x$Dx,perl=TRUE,]))

but I get the error:

Error in x$Dx : $ operator is invlaid for atomic vectors

Answer Source

we could do something like this:

list <- split(mtcars, mtcars$cyl)
sapply(list, function(x) sum(grepl("2", x$carb)))

we would get a named vector as output:

4 6 8 
6 0 4 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download