dataframe - 我可以制作一个使用循环制作像这样的数据框的函数吗?(后续问题)
问题描述
感谢您对这个问题感兴趣。
我有如下数据。
a<- data.frame("Grade"=c(1, 2, 3, 4), "Prob"=c(0.01, 0.25, 0.45, 0.29))
b<- data.frame("Pot"= c(letters[1:18]))
基于下面的代码,我想制作一个函数,它可以根据概率(替换=真)和四个具有相同概率(替换=假)的随机字母循环 4 个等级数字。例如,这个循环可能如下所示:
3 2 3 2 d f k g
1 3 4 2 a k r b
我想做一个函数,它不仅可以计算 Grades 结果仅低于 3 的结果,并且我选择的四个字母出现,而且可以计算得到这个结果的试验次数。因此,如果我希望 Pot 具有“a”、“b”、“c”和“d”,结果将如下所示:
Trial Grade Pot
15 3 2 1 3 a b c d
39 2 1 2 2 d b a c
2 3 3 3 3 d a b d
77 3 2 3 3 c d b a
感谢一个非常善良的人,我可以学习下面的代码,但我无法编辑它以获得我希望看到的结果。你能帮我么?
samplefun <- function(a) {
c <- sample(a$Grade, size=4, prob=a$Prob, replace=TRUE)
res <- tibble(
Trial = which(c < 3)[1],
Result = c[which(c < 3)[1]]
)
nsamples <- 1000
x<-map_dfr(1:nsamples, ~ samplefun(a))
感谢您阅读这个问题。
解决方案
这是我认为您所追求的解决方案。我在采样时没有指定概率向量b$Pot
,因为你没有在你的问题中给出一个长度为 18 个元素的向量(见我的评论)。
library(tidyverse)
a<- data.frame(Grade =c(1, 2, 3, 4), Prob = c(0.01, 0.25, 0.45, 0.29))
b<- data.frame(Pot = letters[1:18])
chosenletters <- c("a", "b", "c", "d")
samplefun <- function(a, b, chosenletters) {
ntrials <- 0
repeat {
grades <- sample(a$Grade, size = 4, prob = a$Prob, replace = T)
chars <- sample(b$Pot, size = 4, replace = F)
ntrials <- ntrials + 1
if (all(grades < 4) & all(chars %in% chosenletters)) {break}
}
return( tibble(Trial = ntrials, Grade = list(grades), Letters = list(chars)) )
}
nsamples <- 5
res <- map_dfr(1:nsamples, ~ samplefun(a, b, chosenletters))
此数据框res
提供嵌入在每个数据框单元格内列表中的正确等级和字母,以及生成结果的试验。
# A tibble: 5 x 3
Trial Grade Letters
<dbl> <list> <list>
1 20863 <dbl [4]> <fct [4]>
2 8755 <dbl [4]> <fct [4]>
3 15129 <dbl [4]> <fct [4]>
4 1033 <dbl [4]> <fct [4]>
5 5264 <dbl [4]> <fct [4]>
嵌套列表的更好视图:
> glimpse(res)
Rows: 5
Columns: 3
$ Trial <dbl> 20863, 8755, 15129, 1033, 5264
$ Grade <list> <3, 3, 3, 3>, <3, 2, 2, 2>, <3, 3, 2, 2>, <3, 3, 2, 3>, <3, 2, 3, 3>
$ Letters <list> <b, a, c, d>, <b, a, c, d>, <c, a, b, d>, <b, d, c, a>, <a, b, d, c>
推荐阅读
- string - 切片显示在列表中的行和列
- ffmpeg - 如何使用ffmpeg在d:/盘中进行批量拆分和批量转换并将输出文件保存在e:/盘中?
- git - 签出以首先提交分支并克隆存储库
- c++ - 类初始化中的指针初始化
- java - 需要消除数组列表中的冗余对象
- airflow - 我是否需要关注 Google Cloud Composer 的 Airflow 调度程序详细信息?
- amazon-web-services - 用于 EC2 SSH 安全检查的 AWS Lambda 函数
- javascript - 我应该如何在 jQuery/AJAX 中使用带有 INSERT/SELECT 的 MySql?
- python - 从 for 循环更新列的数据类型
- api - API 版本控制问题 .NET Core 2.2 UnsupportedApiVersion