user3532423
user3532423

Reputation: 27

Randomly-Assign 0, 1 variable based on ID existing Data.frame

I have received a list containing an ID (from A-J - which is actually more of a name) with multiple observations per ID, a level of consumption and a date. The data.frame looks something like this:

ID(name) Date     Consumption
A        Jan2012  10
A        Feb2012  13
A        Mar2012  14
B        Jan2012  4
B        Feb2012  5

Now I would like to assign randomly each ID a gender which I do using the following code:

sample(0:1,length(final.scenario.1$Customer.id),replace=T)

The problem with using my code above is, that I use for the same participant several different sexes (A is sometimes 0 and sometimes 1 - but I would like to have if A is 0 then it stays 0 and only assigns B 1 or 0 randomly) Can anyone help me out here?

Btw. I have found the following post which was too advanced for me though: Create new data frame columns with binary (0/1) data based on text strings in existing column in R

Kind regards

Upvotes: 0

Views: 1398

Answers (1)

CHP
CHP

Reputation: 17189

You should first create a "gendertable" based on unique values of ID. Then you can merge this table with your data.frame DF to get what you want.

DF
##   ID    Date Consumption
## 1  A Jan2012          10
## 2  A Feb2012          13
## 3  A Mar2012          14
## 4  B Jan2012           4
## 5  B Feb2012           5

set.seed(1234)
gendertable <- data.frame(ID = unique(DF$ID), GENDER = sample(0:1, length(unique(DF$ID)), replace = T))
gendertable
##   ID GENDER
## 1  A      0
## 2  B      1

merge(gendertable, DF)
##   ID GENDER    Date Consumption
## 1  A      0 Jan2012          10
## 2  A      0 Feb2012          13
## 3  A      0 Mar2012          14
## 4  B      1 Jan2012           4
## 5  B      1 Feb2012           5

Upvotes: 3

Related Questions