带purrr::cross\n的笛卡尔乘积滤波
我正在尝试一些带purrr::cross\n的笛卡尔乘积滤波,r,purrr,R,Purrr,我正在尝试一些purrr习惯用法,特别是在一个data.frame中循环(或应用,如果您愿意)函数并与另一个data.frame中的所有其他行进行比较的函数。。。并根据该比较函数过滤笛卡尔积 > df1 chr start end (fctr) (int) (int) 1 chr1 9069 9176 2 chr1 10460 11368 3 chr1 34633 35625 4 chr1 3679
purrr
习惯用法,特别是在一个data.frame中循环(或应用,如果您愿意)函数并与另一个data.frame中的所有其他行进行比较的函数。。。并根据该比较函数过滤笛卡尔积
> df1
chr start end
(fctr) (int) (int)
1 chr1 9069 9176
2 chr1 10460 11368
3 chr1 34633 35625
4 chr1 36791 37023
> df2
chr start2
(fctr) (dbl)
1 chr1 9169
2 chr1 10360
3 chr1 34633
因此,一个简单的示例函数是:
> is.between <- function(x1, y1, y2){
ifelse(x1 >= y1 & x1 <= y2, TRUE, FALSE)
}
然后我天真地尝试像这样使用purr::cross\n
函数
> cross_n(list(df2$start2, df1$start, df1$start), .filter = is.between)
当然,这是行不通的,它通过3个输入列(48个组合)的笛卡尔积进行搜索。我希望搜索df2$start2
vs[df1$start
和df1$end
]的组合(12个组合)
那么…在purrr
框架内有没有一种方法可以做到这一点
用
cross\n
或cross2
和errr不能完全理解它。。我不完全理解cross\u d
OK FWIW上的文档-我已经修改了一些purr::cross\u n
函数来回答我自己的问题。新函数cross2d
如下所示:
# this makes sense only if the .l in the same groups are the same length
# ie they are probably from the same data.frame
cross2d<- function(.l, groups = NULL, .filter = NULL){
if (is_empty(.l) | is.null(groups)) {
return(.l)
}
if (!is.null(.filter)) {
.filter <- as_function(.filter)
}
n <- length(.l)
#separate df for each group
df1<- data.frame(.l[groups==0])
df2<- data.frame(.l[groups==1])
exp.coords<-expand.grid(1:nrow(df1), 1:nrow(df2))
df<- data.frame(df1[exp.coords$Var1,], df2[exp.coords$Var2,])
names(df)<-c(colnames(df1),colnames(df2))
df[do.call(.filter, unname(df)),]
}
我已经为两组(data.frames)和data.frames输出编写了代码。。但是有可能进一步推广…?我不认为这是一个通过
purr
改进的问题。我建议查看数据。table::foverlaps()
@DMC thx看起来很有趣,但是。between
只是一个例子。我真正感兴趣的是笛卡尔组合的这种控制。如果存在一个优雅的解决方案,我可以在很多地方使用它。ifelse(x1>=y1&x1=y1&x1@Frank Nope)之间有什么区别吗?我只是认为这是一个明确的例子。
# this makes sense only if the .l in the same groups are the same length
# ie they are probably from the same data.frame
cross2d<- function(.l, groups = NULL, .filter = NULL){
if (is_empty(.l) | is.null(groups)) {
return(.l)
}
if (!is.null(.filter)) {
.filter <- as_function(.filter)
}
n <- length(.l)
#separate df for each group
df1<- data.frame(.l[groups==0])
df2<- data.frame(.l[groups==1])
exp.coords<-expand.grid(1:nrow(df1), 1:nrow(df2))
df<- data.frame(df1[exp.coords$Var1,], df2[exp.coords$Var2,])
names(df)<-c(colnames(df1),colnames(df2))
df[do.call(.filter, unname(df)),]
}
> cross2d(list(x1=df2$start, x2=df1$start, y2=df1$end), group=c(0,1,1), .filter=is.between)
x1 x2 y2
1 9169 9069 9176
3.2 34633 34633 35625