2017-04-13 104 views
1

如果我開始與向量1在特定位置的特定值,和測試向量以查看哪些項等於1:創建具有基於另一矢量

vector1 <- c(0, 1, 1, 1, 0, 1, 1, 1, 0, 1) 

test <- which(vector1 == 1) 

測試現在等於:2,3,4,6, 7,8,10

然後,我想隨機選擇兩個項目的測試:

sample_vector <- sample(test, 2, replace = FALSE) 

上面的代碼生成的sample_vector:6,3

我的問題是我如何採取sample_vector並把它變成:

vector2 <- 0, 0, 1, 0, 0, 1, 0, 0, 0, 0 

我基本上希望只在sample_vector項目分配到等於1,並從向量1其餘項目被指派爲等於0(即所以它看起來像vector2)。 vector1需要在vector1(10個項目)上具有相同的長度。

謝謝!

+1

'替換(整數(長度(向量1)),sample_vector,1)'' – 989

+0

平板狀(sample_vector,長度(向量1))'' –

回答

1
vector2 <- rep(0, length(vector1)) 
vector2[sample_vector] <- 1 
0

使用此代碼。

vector2 <- rep(0,len(vector1)) 
vector2[sample_vector] = 1 
1
set.seed(44) 
vector1 <- c(0, 1, 1, 1, 0, 1, 1, 1, 0, 1) 
test <- which(vector1 == 1) 
sample_vector <- sample(test, 2, replace = FALSE) 
sample_vector 
#[1] 8 3 

replace(tabulate(seq_along(vector1)) - 1, sample_vector, 1) 
#[1] 0 0 1 0 0 0 0 1 0 0 
+0

replace'似乎是多餘的 –