[英]New variable with uniform random number bounded by constant and second variable value
我正在尝试创建一个介于3和最大列数之间的随机数。
创建一个样本数据框进行复制。
ID <- c(1:10)
max <- c(5,3,7,6,10,4,3,3,5,6)
df <- data.frame(ID,max)
我想要第三列是介于3和最大之间的随机数。
ID max
1 5
2 3
3 7
4 6
5 10
6 4
7 3
8 3
9 5
10 6
我尝试了以下多种变体。
for(i in 1:nrow(df)){
df$rand[i] <- sample((3:df$max[i]),1,replace=TRUE)
}
问题是随机数不在3和max的范围内。 请参阅第8行。我将种子设置为1234。
ID max rand
1 1 5 3
2 2 3 3
3 3 7 4
4 4 6 4
5 5 10 5
6 6 4 4
7 7 2 3
8 8 3 2
9 9 5 4
10 10 6 3
感谢您的帮助。 我仍在学习R并在代码中苦苦挣扎。
df$rand <- sapply(df$max, function(max) round(runif(1, 3, max)))
您的第7行的max = 2
,这就是为什么我们得到NaN
。
ID max rand
1 1 5 4
2 2 3 3
3 3 7 4
4 4 6 4
5 5 10 3
6 6 4 4
7 7 2 NaN
8 8 3 3
9 9 5 4
10 10 6 4
使用transform
另一种选择是照顾最大<3的情况
transform(dat,y = sapply(max,function(x)floor(runif(1,3,if(x>3)x else 3))))
ID max y
1 1 5 4
2 2 3 3
3 3 7 6
4 4 6 4
5 5 10 9
6 6 4 3
7 7 2 3
8 8 3 3
9 9 5 3
10 10 6 3
您也可以仅在某些约束下继续使用sample
(并避免使用floor
或round
)
df$rand <- sapply(seq_len(dim(df)[1]), function(x) if(df$max[x] > 3) sample(3:df$max[x], 1, replace = T) else 3)
## ID max rand
##1 1 5 3
##2 2 3 3
##3 3 7 6
##4 4 6 5
##5 5 10 7
##6 6 4 4
##7 7 2 3
##8 8 3 3
##9 9 5 4
##10 10 6 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.