[英]how to assign one of two values in R based on conditions and number of occurrences
我有一个数据框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 ,以便对于每个Trial and Route ,如果Target等于0,则Random中的值可以随机为1或0。重要的是,对于每个Trial和Route I结束由五个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的更随机分配,但又满足五个1和五个0的要求?
任何建议将不胜感激。 谢谢。
期望:“ ...随机分配值1和0,但满足五个1和五个0的要求”
策略:这基本上是对“向量置换”的要求
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,但这只能传递一行,而Random分配为1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.