在 Dataframe - R 中的每组 ID 中随机分配一个整数
Randomly assign an integer within each group of ID's in Dataframe - R
我正在尝试在每组现有 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
我需要它是动态的,因为每周可能会有更多 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)))
}
提前感谢您的帮助!
您可以使用基本函数 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()))
我正在尝试在每组现有 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
我需要它是动态的,因为每周可能会有更多 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)))
}
提前感谢您的帮助!
您可以使用基本函数 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()))