从矢量采样并保持零频率

时间:2015-05-13 13:00:06

标签: r

我想从矢量替换样本。例如:

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

有没有办法获得一个包含“one”freq的数据帧,其中value为0:

Var1 Freq

1 three    4
2   two    1
3   one    0

1 个答案:

答案 0 :(得分: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