2017-08-29 42 views
0

使用不同的概率行具有这样的数据帧:随机分配不同的值,以作为R

ID var 
1 NA 
2 NA 
3 NA 
4 NA 
... 

我需要随机地分配20个%的行var值是A,和30%的行为B,和50%的行是C.

有没有一些有效的方法来解决这个问题?

+3

'体(C( “A”, “B”, “C”),nrow(df),prob = c(0.2,0.3,0.5),replace = TRUE)'随机抽样,但因为它是随机的,所以不会以20/30/50分割 - 你需要吗? d比例是准确的还是你想根据这些概率进行抽样? – Marius

回答

0

假设你有数据框名为DF: 那么你可以这样写:

randvar = sample(c('A','B','C'),size = nrow(df),prob = c(0.2,0.3,0.5),replace = TRUE) 
df$var = randvar 

假设你想要的 “A” s是正确的20%%,因此,做30% “B” 和 “C”在50% 那么它是不是一个行代码,假设你的C(0.2,0.3,0.5)* df_size是所有整我的回答是:

n = nrow(df) 
df$var = "C" #initialize all value to be "C" 
index = 1:n 
indexa = sample(index,0.2*n) #pick 20% index for "A" 
indexb = sample(index[-indexa],0.3*n) #pick 30% index for "B" need to rule out the "A"s you already picked 
df$var[indexa] = "A" #assign "A" to df$var at indexa 
df$var[indexb] = "B" #assign "B" to df$var at indexb 
#the rest 50% is "C" 
+0

并且如果c(0.2,0.3,0.5)* df_size不是整数,则需要用round(0.2 * n)替换0.2 * n,round(0.3 * n)替换为0.3 * n等等 – cloudscomputes