Say I have a data.frame and I want to subset this data by different filter and get a list of them, so I tried this:
df <- data.frame(A=c(1,2,3), B=c(7,8,9))
filter_lst <- list(c(1,2), c(2,3))
filter_by_range <- function(df, filter) {
with(df, {df[A >= filter[1] &
A < filter[2], ]})
}
mapply(filter_by_range, df, filter_lst)
But it shows error:
Error in eval(substitute(expr), data, enclos = parent.frame()) :
numeric 'envir' arg not of length one
Called from: with.default(df, {
df[A >= filter[1] & A < filter[2], ]
})
I guess it's because df
is taken as a list for mapply
, how can mapply
take df
as a whole or any other better approaches to do this job?
As described in comments above:
mapply(filter_by_range, filter=filter_lst, MoreArgs=list(df))
[,1] [,2]
A 1 2
B 7 8
Notice that it was returned as a matrix because the default is SIMPLIFY=TRUE. If you wanted it as a list:
> mapply(filter_by_range, filter=filter_lst, MoreArgs=list(df), SIMPLIFY=FALSE)
[[1]]
A B
1 1 7
[[2]]
A B
2 2 8
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.