将功能应用于一个表的每个条目到另一个表的每个条目 [英] Apply function over every entry one table to every entry of another
本文介绍了将功能应用于一个表的每个条目到另一个表的每个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用bandstib
library(tidyverse)
set.seed(1)
n <- 5
loss <- rbeta(n, 1, 10) * 100
loss.tib <- loss %>% as_tibble %>% mutate(loss = value) %>% mutate(lossid =
row_number()) %>% select(lossid, loss)
bandstib <- tibble(bandid = seq(4),
start = seq(0, 75, by = 25),
end = seq(25, 100, by = 25))
bandedlossfn <- function(loss, start, end) {
pmin(end - start, pmax(0, loss - start))
}
根据下面的答案,以下代码将产生计算结果:
As per the answer below the following code produces the calculation:
loss.tib %>%
mutate(
result = map(
loss, ~ tibble(result = bandedlossfn(.x, bandstib$start, bandstib$end))
)
) %>% unnest
但是我想将bandid
作为索引包含在map函数中,并将filter(!near(result,0))
附加于map函数中.
However I'd like to include the bandid
as the index within the map function and additionally filter(!near(result,0))
with the map function.
结果应为:
lossid loss bandid result
1 21.6691088 1 21.6691088
2 6.9390647 1 6.9390647
3 0.5822383 1 0.5822383
4 5.5671643 1 5.5671643
5 27.8237244 1 25.0000000
5 27.8237244 2 2.8237244
推荐答案
以下是使用purrr
包中的map2
的一种可能性:
here is one possibility using map2
from the purrr
package:
bandstib %>%
mutate(result = map2(start, end, ~bandedlossfn(loss.tib[[1]], .x, .y)))
根据您希望输出的内容,可以从此处继续操作,例如使用unnest
.
Depending on how you want your output to be you can continue from there by e.g. using unnest
.
编辑
以下是使用map
而不是map2
的相反方法:
Here is how you can apply it the otherway arround using map
instead of map2
:
loss.tib %>%
mutate(result = map(value, bandedlossfn, start = bandstib$start, end = bandstib$end)) %>%
unnest() %>%
mutate(bandid = rep(seq(4), n))
这篇关于将功能应用于一个表的每个条目到另一个表的每个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文