我有一个数据框 DF2 。这是我的数据框的简短版本的可重现示例:
Scene2 = rep(c(1:10), times=9)
myDF2 <- data.frame(Scene2)
myDF2$Target <- rep(0,10, each=9)
myDF2$Target[myDF2$Scene2==7] <- 1 #actually, in my dataframe Scene2 could be equal to any number (not always 7) for Target to be equal to 1, but for simplicity I created this reproducible code.
myDF2$Trial <- rep(c(1:9),each=10)
myDF2$Route <- rep(LETTERS[1:6], each=10, length=nrow(myDF2))
我想创建一个新列 Random ,这样每个试用和路由,如果目标等于0,那么 Random 中的值可以随机为1或0.重要的是每个 Trial 和 Route 我最终得到五个1和五个0(当 Target 等于1时, Random 总是为1)。 以下代码有效,但订单看起来并不随机。
library(plyr)
myDF3 <- myDF2 %>% group_by(Trial, Route) %>%
mutate(Random = ifelse(myDF2$Target==0,sample(c(0,1),replace=T, prob=c(0.5,0.5)),1)) %>% as.data.frame()
这给了我结果:
Scene2 Target Trial Route Random #I would like something more random, just an example:
1 0 1 A 1 #0
2 0 1 A 0 #0
3 0 1 A 1 #0
4 0 1 A 0 #0
5 0 1 A 1 #0
6 0 1 A 0 #1
7 1 1 A 1 #1
8 0 1 A 0 #1
9 0 1 A 1 #1
10 0 1 A 0 #1
1 0 2 B 1 #1
2 0 2 B 0 #0
3 0 2 B 1 #1
4 0 2 B 0 #0
5 0 2 B 1 #1
6 0 2 B 0 #0
7 1 2 B 1 #1
8 0 2 B 0 #0
9 0 2 B 1 #1
10 0 2 B 0 #0
1 0 3 C 1 #1
2 0 3 C 0 #1
3 0 3 C 1 #0
4 0 3 C 0 #0
5 0 3 C 1 #1
6 0 3 C 0 #0
7 1 3 C 1 #1
8 0 3 C 0 #0
9 0 3 C 1 #1
10 0 3 C 0 #0
1 0 4 D 1 #1
2 0 4 D 0 #1
3 0 4 D 1 #1
4 0 4 D 0 #1
5 0 4 D 1 #0
6 0 4 D 0 #0
7 1 4 D 1 #1
8 0 4 D 0 #0
9 0 4 D 1 #0
10 0 4 D 0 #0
如何创建值1和0的更随机的分配,但是满足5个1和5个0的要求?
非常感谢任何建议。谢谢。
答案 0 :(得分:1)
期望:&#34; ...随机分配值1和0,但满足5和1的要求0&#34;
策略:这基本上是对矢量排列的请求&#34;
set.seed(123) # needed for reproducibility
sample( c(rep(1,5),rep(0,5) ) )
#[1] 1 0 1 0 0 1 0 0 1 1
您可能不应该在tidyverse中使用library(plyr)
。它往往会产生模糊的错误。随着tidyverse加载而不是plyr我得到:
myDF3 <- myDF2 %>% group_by(Trial, Route) %>%
mutate(Random = ifelse(Target==0,
sample(c(rep(0,5),rep(1,5))),
rep(1,10) )) %>%
as.data.frame()
虽然在Target == 0正确的情况下它已经得到排列,但我不确定是否需要它。我没有理解的是Target == 1的情况是否被正确分配。我原以为你打算有10行的1行,但是只提供一行,随机分配给1。