Reputation: 910
I want to aggregate all rows of data frames within a list which have the same character in a column. For this I used
lapply(lst, function(x) aggregate(Value ~ Area, x, sum))
which works fine. However, I get also empty dfs in my list (which I need, so I cannot drop them) and I get an error:
Error in aggregate.data.frame(mf[1L], mf[-1L], FUN = FUN, ...) :
no rows to aggregate
Is there a way to overcome this error? Thanks. Below a small example:
lst <- list("111.2012"=data.frame("Area"=character(0), "Value"=numeric(0)),
"112.2012"=data.frame("Area"=c("a","b","b","a"), "Value"=c(1,5,3,2)))
Upvotes: 1
Views: 182
Reputation: 10513
lst <- list("111.2012"=data.frame("Area"=character(0), "Value"=numeric(0)),
"112.2012"=data.frame("Area"=c("a","b","b","a"), "Value"=c(1,5,3,2)))
lapply(lst, function(x) if (nrow(x)) aggregate(Value ~ Area, x, sum) else x)
Output
$`111.2012`
[1] Area Value
<0 rows> (or 0-length row.names)
$`112.2012`
Area Value
1 a 3
2 b 8
Upvotes: 3