% map_df(~rbinom(n, 1, prob = .5)) %>% rowwise() %>% muta-6ren">
gpt4 book ai didi

R 使用 purrr 的多个循环,其中输出是数据表/tibble/矩阵

转载 作者:行者123 更新时间:2023-12-04 13:08:01 25 4
gpt4 key购买 nike

rc<-1 # the number of red balls
wc<-1 # the number of white balls
red<-rep("Red",rc)
white<-rep("White",wc)
jar<-c(red,white)
nb<-5 ### number of draws
N=10 # Number of experiments
new_data<-matrix(NA,nrow = N,ncol = nb+1)
count_red_new<-matrix(NA,nrow = N,ncol = nb)
red_count<-rep(NA,N)
#### nested loop
for(i in 1:N){
for(j in 1:nb){
new_data[i,j]<-sample(jar,1,replace = T)
if(new_data[i,j]=="Red"){
count_red_new[i,j]=1
}else{
count_red_new[i,j]=0
}
red_count[i]=sum(count_red_new[i,])
new_data[i,nb+1]=red_count[i]
}
}
colnames(new_data)<-c("Draw1","Draw2","Draw3","Draw4","Draw5","Red Ball Count")
new_data<-data.frame(new_data)
#new_data$Red.Ball.Count<-as.integer(new_data$Red.Ball.Count)
new_data

上面的代码用于运行关于在 5 次抽取中拉动红球和白球的实验。本实验进行 10 次迭代。如上所述,我在两者之间使用了一个嵌套循环。如何将 purrr 用于嵌套循环,以便输出可以存储在矩阵或数据框中?

最佳答案

这是使用 map 的一种方法。如果您只有红球和白球,则可以利用 rbinom() 进行平局。假设平局 1 是红球。

library(tidyverse)

nb <- 1:5
n <- 10

nb %>%
set_names(paste0("draw", .)) %>%
map_df(~rbinom(n, 1, prob = .5)) %>%
rowwise() %>%
mutate(red_ball_count = sum(c_across(everything())))

# A tibble: 10 x 6
# Rowwise:
draw1 draw2 draw3 draw4 draw5 red_ball_count
<int> <int> <int> <int> <int> <int>
1 1 1 1 0 0 3
2 0 1 0 0 1 2
3 0 0 0 1 1 2
4 0 0 0 1 1 2
5 1 0 0 0 0 1
6 1 0 1 0 1 3
7 1 0 1 1 1 4
8 0 0 1 0 1 2
9 1 1 0 1 0 3
10 0 1 0 1 1 3

请注意,这在技术上执行了 5 轮 10 次平局而不是 10 轮 5 次平局。如果真要10轮5抽,也是一样的思路,不过需要用t()转置。

FWIW 这是一个基本的 R 方法:

df <- data.frame(t(replicate(n, rbinom(nb, 1, prob = .5))))
colnames(df) <- gsub("X", "Draw", colnames(df))
df['red_ball_count'] <- rowSums(df)

最后,鉴于伯努利试验中的顺序(通常)无关紧要,请注意您可以通过指定 单独使用 rbinom() 获得 red_ball_count n=10size=5:

rbinom(n, nb, prob = .5)

关于R 使用 purrr 的多个循环,其中输出是数据表/tibble/矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68504505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com