[英]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.