【问题标题】:Randomly assign an integer within each group of ID's in Dataframe - R在 Dataframe 中的每组 ID 中随机分配一个整数 - R
【发布时间】: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


【解决方案1】:

您可以使用基本函数 ave 来做到这一点

dd <- data.frame(Groups = rep(c("A","B","C"), c(4,8,6)))
rand_seq_for <- function(x) sample.int(length(x))
dd$rand_int <- ave(1:nrow(dd), dd$Groups, FUN=rand_seq_for)

或者使用dplyr,你可以这样做

library(dplyr)
dd %>% group_by(Groups) %>% mutate(rand_int=sample.int(n()))

【讨论】:

  • 感谢您提供两个出色的解决方案,dplyr 解决方案正是我想要的!
猜你喜欢
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
  • 2016-01-09
  • 2015-10-21
  • 2020-10-12
  • 2021-02-21
  • 2021-04-11
相关资源
最近更新 更多