MonteCarlo 模拟 - 创建 100 data.frames 行随机分组,后续天数固定
MonteCarlo simulation - Create 100 data.frames with rows grouped randomly with a fixed number of subsequent days
这是我的 data.frame 的一个例子,我们假设 date
col 代表天数:
df = read.table(text = 'ID date
a 1
a 2
a 3
a 4
a 7
a 12', header = TRUE)
所以,我在这里的日子从 1 到 12 不等,我想创建 100 个 data.frames,其中每个 date
(和 ID
)col 将被分组随后 3 天随机生成。
例如
df1
ID date group
a 1 1 #group 1 = 1, 2, 3
a 2 1
a 3 1
a 4 2 # group 2 = 4, 5, 6
a 7 3 # group 3 = 7, 8, 9
a 12 4 # group 4 = 10, 11, 12
df2
ID date group
a 1 4
a 2 1 #group 1 = 2, 3, 4
a 3 1
a 4 1
a 7 2 #group 2 = 5, 6, 7 --- group 3 = 8, 9, 10
a 12 4 # group 4 = 11, 12 and start again from the beginning 1
df3
ID date group
a 1 1
a 2 1
a 3 2 #group 2 = 3, 4, 5
a 4 2
a 7 3 #group 3 = 6, 7, 8 -- group 4 = 9, 10, 11
a 12 1 #group 1 = 12, 1, 2
等...
请注意,group
col 通过考虑不一定出现在 data.frame 中的后续日期将行按 3 分组,并且整个技巧的随机性是第 1 组的开始日期。
你有什么建议吗?
不确定,但您可以创建一个空列表并填充类似于您的示例的新数据框:
set=list()
for(i in 1:100) { set[[i]] = cbind(df,group=sample(rep(c(1,2),each=3))) }
这是我的 data.frame 的一个例子,我们假设 date
col 代表天数:
df = read.table(text = 'ID date
a 1
a 2
a 3
a 4
a 7
a 12', header = TRUE)
所以,我在这里的日子从 1 到 12 不等,我想创建 100 个 data.frames,其中每个 date
(和 ID
)col 将被分组随后 3 天随机生成。
例如
df1
ID date group
a 1 1 #group 1 = 1, 2, 3
a 2 1
a 3 1
a 4 2 # group 2 = 4, 5, 6
a 7 3 # group 3 = 7, 8, 9
a 12 4 # group 4 = 10, 11, 12
df2
ID date group
a 1 4
a 2 1 #group 1 = 2, 3, 4
a 3 1
a 4 1
a 7 2 #group 2 = 5, 6, 7 --- group 3 = 8, 9, 10
a 12 4 # group 4 = 11, 12 and start again from the beginning 1
df3
ID date group
a 1 1
a 2 1
a 3 2 #group 2 = 3, 4, 5
a 4 2
a 7 3 #group 3 = 6, 7, 8 -- group 4 = 9, 10, 11
a 12 1 #group 1 = 12, 1, 2
等...
请注意,group
col 通过考虑不一定出现在 data.frame 中的后续日期将行按 3 分组,并且整个技巧的随机性是第 1 组的开始日期。
你有什么建议吗?
不确定,但您可以创建一个空列表并填充类似于您的示例的新数据框:
set=list()
for(i in 1:100) { set[[i]] = cbind(df,group=sample(rep(c(1,2),each=3))) }