【发布时间】:2017-03-29 19:16:40
【问题描述】:
我正在尝试在每组现有 ID 中设置一个随机整数。整数必须满足以下条件:唯一、不重复,并且一组 ID 的最大整数不会大于具有该 ID 的行数。
我尝试在 for 循环中执行此操作,它适用于第一组 ID,但不会重复下一组。我查看了几个现有的堆栈溢出问题和其他网站,它们在某种程度上解决了这个问题,但仍然无法正确解决。以下链接:
Randomly Assign Integers in R within groups without replacement
http://r.789695.n4.nabble.com/Random-numbers-for-a-group-td964301.html
random selection within groups
我需要它是动态的,因为每周可能会有更多的 ID 或更少的 ID。实际的 DF 有几个其他列,但为了便于复制,它们被省略了,因为它们没有被使用。
下面的例子:
#Desired Output
Groups <- c("A","A","A","A","B","B","B","B","B","B","B","B","C","C","C","C","C","C")
Desired_Integer <- c(1,4,2,3,6,3,1,2,8,5,7,4,5,6,1,4,3,2)
Example <- data.frame(Groups,Desired_Integer)
#Attempted For Loop for Example (assuming Example is a DF with one column, Groups for the For Loop)
Groups <- c("A","A","A","A","B","B","B","B","B","B","B","B","C","C","C","C","C","C")
Example <- as.data.frame(Groups)
for (i in Example$Groups)
{
Example$Desired_Integer <- sample.int(length(which(Example$Groups == i)))
}
提前感谢您的帮助!
【问题讨论】:
-
会做的,谢谢你的提示!
标签: r for-loop integer sampling