映射中的谓词函数
predicate function in map
我最近一直在研究 purrr
族函数,在阅读 map_if
的文档时,我遇到了 .p
参数的另一种定义形式。我无法理解的谓词函数。它说:
"Alternatively, if the elements of .x are themselves lists of objects,
a string indicating the name of a logical element in the inner lists"
我想知道您能否告诉我它的含义以及在我处理其元素也是列表的列表时如何使用它。像这样:
x <- list(a = list(foo = 1:2, bar = 3:4), b = list(baz = 5:6))
一个简单的例子将不胜感激,因为我已经做了一些研究但找不到任何迹象。
非常感谢您。
虽然我不太确定你到底想了解什么,但是以list of lists为例,我们需要考虑这里只有map_if
可用,pmap_if
不可用.让我们再看一个列表,而不是你建议的列表。
x <- list(a = list(foo = 1:2, bar = 3:4), b = list(baz = 5:6), c = list(bird = 7:10))
现在 map_if
在 .p
是 T
的地方应用 .f
。因此,如果我们想对列表 x 中的所有奇数索引列表取平均值,我们实际上必须再次使用嵌套 map
。
见
map_if(x, as.logical(seq_along(x) %% 2) , ~map(.x, ~mean(.x)))
$a
$a$foo
[1] 1.5
$a$bar
[1] 3.5
$b
$b$baz
[1] 5 6
$c
$c$bird
[1] 8.5
我们还可以在 .p
中使用其他谓词函数。下面的例子产生相同的输出。
map_if(x, names(x) %in% c("a", "c") , ~map(.x, ~mean(.x)))
或者假设 x
的名称类似于这样
x <- list(val1 = list(foo = 1:2, bar = 3:4), ind1 = list(baz = 5:6), val2 = list(bird = 7:10))
然后下面的语法将产生类似的结果
map_if(x, str_detect(names(x), "val") , ~map(.x, ~mean(.x)))
我希望这有点接近你可能想要了解的。
P.S。您也可以 it 阅读。
我最近一直在研究 purrr
族函数,在阅读 map_if
的文档时,我遇到了 .p
参数的另一种定义形式。我无法理解的谓词函数。它说:
"Alternatively, if the elements of .x are themselves lists of objects, a string indicating the name of a logical element in the inner lists"
我想知道您能否告诉我它的含义以及在我处理其元素也是列表的列表时如何使用它。像这样:
x <- list(a = list(foo = 1:2, bar = 3:4), b = list(baz = 5:6))
一个简单的例子将不胜感激,因为我已经做了一些研究但找不到任何迹象。
非常感谢您。
虽然我不太确定你到底想了解什么,但是以list of lists为例,我们需要考虑这里只有map_if
可用,pmap_if
不可用.让我们再看一个列表,而不是你建议的列表。
x <- list(a = list(foo = 1:2, bar = 3:4), b = list(baz = 5:6), c = list(bird = 7:10))
现在 map_if
在 .p
是 T
的地方应用 .f
。因此,如果我们想对列表 x 中的所有奇数索引列表取平均值,我们实际上必须再次使用嵌套 map
。
见
map_if(x, as.logical(seq_along(x) %% 2) , ~map(.x, ~mean(.x)))
$a
$a$foo
[1] 1.5
$a$bar
[1] 3.5
$b
$b$baz
[1] 5 6
$c
$c$bird
[1] 8.5
我们还可以在 .p
中使用其他谓词函数。下面的例子产生相同的输出。
map_if(x, names(x) %in% c("a", "c") , ~map(.x, ~mean(.x)))
或者假设 x
的名称类似于这样
x <- list(val1 = list(foo = 1:2, bar = 3:4), ind1 = list(baz = 5:6), val2 = list(bird = 7:10))
然后下面的语法将产生类似的结果
map_if(x, str_detect(names(x), "val") , ~map(.x, ~mean(.x)))
我希望这有点接近你可能想要了解的。
P.S。您也可以 it 阅读。