如何循环遍历dplyr中的数字
How to loop through numbers in dplyr
我写了一个查询,根据百分比 (A) 给出误报的数量。我想计算出不同百分比会产生多少误报。
我知道我每次都可以更改 A,但我想使用最小 A、最大 A 和介于 (10, 20 ..., 100) 之间的每 10 个数字来自动执行该过程
示例代码
df <- tibble("id" = 1:100, "Perc_change" = rnorm(100, mean = 15, sd = 5), "v1" = rnorm(100, mean = 0, sd = 4))
A <- 10
df %>%
mutate(x1 = if_else(Perc_change > A, 1, 0),
x2 = if_else((Perc_change > A) & (v1 > 0 )), 1, 0)) %>%
select(x1,x2) %>%
summarise(perc = A,
true = sum(x1 ==1),
false = sum(x1 == 1 & x2 == 0),
true_perc = true/(true+false)*100)
我想要一个 table 显示 A 的值,true,false,true_perc 对于不同的 A 值。
这是我的table
的当前输出
A true false true_perc
10 120 80 60
我希望 table 是这样的:
A true false true_perc
10 19721 33767 37
20 18541 29720 38
...
100 10203 11431 47
如果我们想循环,我们可以使用map
from purrr
library(tidyverse)
map_df(seq(10, 100, by = 10), ~
df %>%
transmute(x1 = as.integer(Perc_change > .x),
x2 = as.integer(x1 & (v1 > 0)) ) %>%
summarise(perc = .x,
true = sum(x1),
false = sum(x1 & !x2 ),
true_perc = true/(true + false) * 100))
我写了一个查询,根据百分比 (A) 给出误报的数量。我想计算出不同百分比会产生多少误报。
我知道我每次都可以更改 A,但我想使用最小 A、最大 A 和介于 (10, 20 ..., 100) 之间的每 10 个数字来自动执行该过程
示例代码
df <- tibble("id" = 1:100, "Perc_change" = rnorm(100, mean = 15, sd = 5), "v1" = rnorm(100, mean = 0, sd = 4))
A <- 10
df %>%
mutate(x1 = if_else(Perc_change > A, 1, 0),
x2 = if_else((Perc_change > A) & (v1 > 0 )), 1, 0)) %>%
select(x1,x2) %>%
summarise(perc = A,
true = sum(x1 ==1),
false = sum(x1 == 1 & x2 == 0),
true_perc = true/(true+false)*100)
我想要一个 table 显示 A 的值,true,false,true_perc 对于不同的 A 值。
这是我的table
的当前输出
A true false true_perc
10 120 80 60
我希望 table 是这样的:
A true false true_perc
10 19721 33767 37
20 18541 29720 38
...
100 10203 11431 47
如果我们想循环,我们可以使用map
from purrr
library(tidyverse)
map_df(seq(10, 100, by = 10), ~
df %>%
transmute(x1 = as.integer(Perc_change > .x),
x2 = as.integer(x1 & (v1 > 0)) ) %>%
summarise(perc = .x,
true = sum(x1),
false = sum(x1 & !x2 ),
true_perc = true/(true + false) * 100))