Reputation: 107
I'm trying to assign a variable in data frame according to specific another column variable. i.e.
Dta = matrix(0,10000,2)
colnames(Dta) <- c("School_ID","Class_ID")
Dta = as_data_frame(Dta)
Dta$School_ID = sample(100)
Dta$School_ID = sort(Dta$School_ID)
for (i in unique(Dta$School_ID) ) Dta[Dta$School_ID == i,'Class_ID'] = sample(5)
Is there any solution by using group_by or other operators without a loop?
Upvotes: 1
Views: 46
Reputation: 39154
Here is a solution from dplyr
. dt2
is the final output.
# Load package
library(dplyr)
dt <- data_frame(School_ID = rep(1:100, each = 100))
dt2 <- dt %>%
group_by(School_ID) %>%
mutate(Class_ID = rep(sample(5), 20))
Upvotes: 1