Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new variable to dataframe equally

using RStudio, I have this :

GROUP NUM
A     45
A     78
A     79  
B     45
B     47
B     99
C     28
C     78
C     54

I want to add a new variable, named AGENT, which is:

AGENT=c("John", "Maria", "Pamela")

But the problem is that, I want each of my Agent to be equally spreaded amongsts the initial dataframe according to the ID. Basically, I want this:

GROUP NUM AGENT
A     45  John
A     78  Maria
A     79  Pamela
B     45  John 
B     47  Maria
B     99  Pamela
C     28  John
C     78  Maria
C     54  Pamela

My example here is basic because I have as many groups as I have agents. However in my case, I might have 70 of each letter (70 A, 70 B and 70 C) and still only 3 agents. I still want them to be spread as equally as possible....

For example, if I had 6 A, I would have :

GROUP NUM AGENT
A     45  John
A     78  Maria
A     79  Pamela
A     48  John
A     97  Maria
A     59  Pamela
...

And if I had 7, then 7th would be assigned randomly, or just the next on the list.

Any ideas? I've been torturing myself over this. Thanks in advance! :P

like image 960
Antly Prvk Avatar asked Sep 17 '26 14:09

Antly Prvk


1 Answers

If "or just the next on the list." is appropriate for any overflow when the group is larger, you can take advantage of vector recycling and just do it in one assignment:

dat$newvar <- with(dat, ave(1:nrow(dat), GROUP, FUN=function(x) AGENT) )
dat
#  GROUP NUM newvar
#1     A  45   John
#2     A  78  Maria
#3     A  79 Pamela
#4     B  45   John
#5     B  47  Maria
#6     B  99 Pamela
#7     C  28   John
#8     C  78  Maria
#9     C  54 Pamela

Just ignore any warnings you might get when the groups are not neatly matched to the size of AGENT

data.table could be used too, in a similar fashion:

library(data.table)
setDT(dat)
dat[, newvar2 := AGENT, by=GROUP]
like image 94
thelatemail Avatar answered Sep 19 '26 02:09

thelatemail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!