简体   繁体   English

在 R 中的列表中映射元素对

[英]mapply on pairs of elements in a lists in R

If I have a symmetric binary operator that I want to apply over the pairs of elements from a list, is there an easy way I can do this in R?如果我有一个对称二元运算符要应用于列表中的元素对,是否有一种简单的方法可以在 R 中执行此操作? I tried:我试过:

A <- list(1,2,3)
mapply(function(x,y) x+y, A,A)

but this only gives x[n]+y[n] for all n=1..N but I want x[n]+y[m] for all m=1..n, n=1..N returned as a list.但这只会为所有n=1..N给出x[n]+y[n]但我想要x[n]+y[m]对于所有m=1..n, n=1..N返回为一个列表。 outer(..) does that for m=1..N, n=1..N which involves redundant computation so I want to discount that. outer(..)m=1..N, n=1..N这样做,这涉及冗余计算,所以我想打折扣。

Notice I don't want solution to this simple example.请注意,我不想要这个简单示例的解决方案。 I need a general solution that works for non-numeric input as well.我需要一个适用于非数字输入的通用解决方案。 The thing I'm trying to do is like:我想做的事情是:

mapply(function(set_1, set_2) intersect(set_1, set_2), list_of_sets, list_of_sets)

In both cases addition and intersection are symmetric.在这两种情况下,加法和交集都是对称的。 In the first example, I expect list(3,4,5) from list(1+2,1+3,2+3) .在第一个示例中,我希望list(3,4,5)来自list(1+2,1+3,2+3)

You may use outer -您可以使用outer -

values <- c(1, 2, 3)
outer(values, values, `+`)

#     [,1] [,2] [,3]
#[1,]    2    3    4
#[2,]    3    4    5
#[3,]    4    5    6

outer also works for non-numeric input. outer也适用于非数字输入。 If the function that you want to apply is not vectorised you can use Vectorize .如果您要应用的函数不是矢量化的,您可以使用Vectorize Since OP did not provide an example I have created one of my own.由于 OP 没有提供示例,因此我创建了自己的示例。

list_of_sets_1 <- list(c('a', 'b', 'c'), c('a'))
list_of_sets_2 <- list(c('a', 'c'), c('a', 'b'))

fun <- function(x, y) intersect(x, y)
result <- outer(list_of_sets_1, list_of_sets_2, Vectorize(fun))
result

We need combn to do pairwise computation without redundancy我们需要combn来做没有冗余的成对计算

combn(A, 2, FUN = function(x) x[[1]] + x[[2]], simplify = FALSE)

-output -输出

[[1]]
[1] 3

[[2]]
[1] 4

[[3]]
[1] 5

This will also work with non-numeric elements这也适用于非数字元素

list_of_sets <- list(c('a', 'b', 'c'), "a", c("a", "c"))
combn(list_of_sets, 2, FUN = function(x) Reduce(intersect, x), simplify = FALSE)

-output -输出

[[1]]
[1] "a"

[[2]]
[1] "a" "c"

[[3]]
[1] "a"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM