0

如何让这段代码更整洁?

as_tibble(t(mapply(pmf, x=lhs$mu, y=lhs$sigma)))

pmf()是一个辅助函数。

pmf <- function(x, y) diff(pnorm(c(-Inf, -2, 0, 2, Inf), x, y))

此代码从每行获取平均值和标准差,并返回每个 bin 的概率质量函数 (PMF)。

所以这

# A tibble: 6 x 4
i     j       mu    sigma
<int> <int>    <dbl>    <dbl>
  1     1     1 1.890402 2.879148
2     1     2 1.202357 2.655255
3     1     3 1.186224 2.127293
4     1     4 1.222278 2.228819
5     1     5 1.760214 2.324657
6     2     1 1.726712 2.574771

变成这个

# A tibble: 6 x 8
i     j       mu    sigma         V1        V2        V3        V4
<int> <int>    <dbl>    <dbl>      <dbl>     <dbl>     <dbl>     <dbl>
  1     1     1 1.890402 2.879148 0.08831027 0.1674140 0.2594582 0.4848175
2     1     2 1.202357 2.655255 0.11390009 0.2114385 0.2927260 0.3819354
3     1     3 1.186224 2.127293 0.06709483 0.2214568 0.3604183 0.3510301
4     1     4 1.222278 2.228819 0.07412598 0.2175836 0.3447228 0.3635676
5     1     5 1.760214 2.324657 0.05288144 0.1715857 0.3166106 0.4589223
6     2     1 1.726712 2.574771 0.07389306 0.1773358 0.2910357 0.4577354

在我bind_cols()用来添加输出之后。

我尝试了以下(使用相同的pmf()辅助函数)。

pmf <- function(x, y) diff(pnorm(c(-Inf, -2, 0, 2, Inf), x, y))
lhs %>% rowwise() %>% do(k = pmf(.$mu, .$sigma))

但它将 PMF 作为列表返回。我希望 PMF 连续。这对我不起作用,因为下游我需要在每列的行中应用一个函数V#

是否有可能使这个计算更整洁?

FWIW,这是完整的计算。

library(tidyverse)

# find PMF from mu and sigma
pmf <- function(x, y) diff(pnorm(c(-Inf, -2, 0, 2, Inf), x, y))

# find mean*variance for each column (i.e., PMF bin) __across rows___
mean_var <- function(x) mean(x)*var(x)

# here are my data
lhs <- tibble(i = rep(1:2, each=5),
              j = rep(1:5, times=2),
              mu = 1 + runif(2*5),
              sigma = 2 + runif(2*5))

# find PMF from mu and sigma
rhs <- as_tibble(t(mapply(pmf, x=lhs$mu, y=lhs$sigma)))

# downstream calculations
ans <- 
  lhs %>% 
  bind_cols(rhs) %>% 
  group_by(i) %>% 
  summarise_at(vars(starts_with('V')), funs(mean_var)) %>% 
  gather(bin, mean_var, -i) %>% 
  group_by(i) %>% 
  summarise(ambg = sum(mean_var))

# this finds PMF from mu and sigma, but as a list; I need a row
lhs %>% rowwise() %>% do(k = pmf(.$mu, .$sigma))
4

0 回答 0