我有一个名为demo的数据框,其中有500条这样的记录
ID Age
1 10
2 15
3 36
4 20
. .
. .
497 40
498 5
499 12
500 20在上面的dataframe中,我想添加具有值的列,这样总记录的25% (在我们的例子中是125)必须在1-3之间,其余的75%(从126开始)必须在4-10之间,这样输出看起来就像这样
ID Age colB
1 10 2
2 15 1
3 36 1
4 20 3
. .
. .
497 40 8
498 5 10
499 12 5
500 20 9我试过了
function(x) {
a= row.names(demo)[125]
a <- FALSE
while (!a) {
demo$colB <- sample(nrow(demo), c(1:3))
}
return(x)
}任何帮助都是非常appreciated.Thanks的
发布于 2017-01-18 13:58:23
我们可以尝试使用rep和sample
demo$colB <- sample(c(rep(1:3, length.out= ceiling(nrow(demo)*.25)),
rep(4:10, length.out=ceiling(nrow(demo)*.75))))[seq_len(nrow(demo))]
sum(demo$colB %in% 1:3)
#[1] 125基于其他帖子计算sum
sum(demo$colB %in% 1:3)
#[1] 121两者都使用set.seed(1)来计算sample (以使其可重现)
数据
set.seed(24)
demo <- data.frame(ID = 1:500, Age = sample(10:99, 500, replace=TRUE))发布于 2017-01-18 14:01:42
试试这个(假设colB中的值不依赖于其他列的值):
demo$colB <- sample(1:10, nrow(demo), prob = c(rep(0.25/3, 3), rep(0.75/7, 7)), replace=TRUE)https://stackoverflow.com/questions/41712293
复制相似问题