2015-05-13 34 views
1

我想從矢量中進行替換採樣。例如:從矢量採樣並保持零頻率

set.seed(11) 
x = as.data.frame(table(sample(c("one", "two", "three"), 5, replace = T, prob = c(0.05, 0.45, 0.5)))) 

回報:

x 

Var1 Freq 
1 three 4 
2 two 1 

有沒有辦法得到一個數據幀將包含 「一個」 頻率,以及,其中值是0:

Var1 Freq 

1 three 4 
2 two 1 
3 one 0 
+1

不是什麼大不了的,你有一個額外的「)」你的代碼的第2行的末尾。對於我來說,編輯太小了,無法制作。 –

回答

2

你可以定義一個因子和樣本:

f_sa <- factor(c("one", "two", "three")) 
x <- as.data.frame(table(sample(f_sa, 5, replace = T, prob = c(0.05, 0.45, 0.5)))) 

x 
# Var1 Freq 
# 1 one 0 
# 2 three 4 
# 3 two 1 

如果你想讓它通過頻率,而不是級別進行排序:

x[order(x$Freq, decreasing=T),] 

# Var1 Freq 
#2 three 4 
#3 two 1 
#1 one 0