rno*_*ian 2 r function list dataframe
Suppose I'm subsetting from a list of named data.frames with respect to a subsetting variable called long.
After subsetting, some data.frames in the list may be empty because there is no match for subsetting in them.
I was wondering how I could delete all such empty data.frames in my final output.
A simple example, and my unsuccessful solution are shown below:
b <- list(Study1 = data.frame(d = 6:8, long = c(F, F,F)), Study2 = data.frame(d = 9:11, long = c(T, T, F)) )
( h <- lapply(b, subset, subset = long) ) ## subset with respect to "long"
## OUTPUT:
$Study1
[1] d long
<0 rows> (or 0-length row.names) ## This data.frame is empty!! must be deleted ##!
$Study2
d long
1 9 TRUE
2 10 TRUE
## I tried the following with no success: ##
for(i in 1:2) if(nrow(h[[i]]) == 0) h[[i]] <- NULL else h[[i]]
Run Code Online (Sandbox Code Playgroud)
Simply Filter by number of rows:
new_list_of_dfs <- Filter(NROW, list_of_dfs)
Run Code Online (Sandbox Code Playgroud)