简体   繁体   English

在 R 的两个命名列表之间应用 function 的最佳方法是什么?

[英]What is the best way to apply a function between two named lists in R?

I have an S3 object structured like this:我有一个 S3 object 结构如下:

dataset <- NULL
dataset$x <- list(a=runif(10), b=runif(10), c=runif(10))
dataset$y <- list(a=runif(10), b=runif(10), c=runif(10))

The two lists $x and $y contain an equal number of elements with the same names.两个列表 $x 和 $y 包含相同数量的同名元素。

I need to apply a function between both lists simultaneously, as follows:我需要同时在两个列表之间应用一个 function ,如下:

for(i in c('a','b','c')){
  subset <- dataset$x[[i]] > 0.5
  dataset$x[[i]] <- subset(dataset$x[[i]], subset)
  dataset$y[[i]] <- subset(dataset$y[[i]], subset)
}

In the real case, the lists have a very large number of elements, so a loop is not the fastest approach.在实际情况下,列表具有非常多的元素,因此循环不是最快的方法。 What is the best way to vectorize this loop?向量化这个循环的最佳方法是什么?

Thank you!谢谢!

Here is one method with lapply/Map .这是lapply/Map的一种方法。 Extract the 'x' element from 'dataset', convert the double list elements to logical ('lst1').从“数据集”中提取“x”元素,将双list元素转换为logical (“lst1”)。 Then loop over the 'dataset' with lapply , use Map inside to subset the inner list with the logical list created with 'x' element ('lst1')然后使用Map lapply “x”元素(“lst1”)创建的逻辑list对内部list进行subset

lst1 <- lapply(dataset$x,`>`, 0.5)
out <- lapply(dataset, function(x) Map(subset, x, lst1))

The advantage is that we don't have to extract the multiple list elements as showed in the OP's post优点是我们不必提取 OP 帖子中显示的多个list元素

-output -输出

out
$x
$x$a
[1] 0.6849740 0.7275233 0.8227778 0.9315966

$x$b
[1] 0.6296180 0.5122322 0.6795041

$x$c
[1] 0.5528317 0.9408803 0.7244978 0.6040235 0.8212669 0.5369701


$y
$y$a
[1] 0.1836949 0.8954276 0.5996935 0.4948389

$y$b
[1] 0.2699243 0.5965194 0.3989432

$y$c
[1] 0.5072449 0.1735438 0.4563791 0.9464107 0.7269070 0.4369199

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

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