Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create ID column in R

Tags:

database

r

I have a longitudinal data in a long format. I want to create an ID variable based on the variable-column that identifies each observation of my data. How do I do that in R?

Example: I have this data

name year var1 var2
 A    1    4    3
 A    2    5    1
 A    3    4    2
 B    1    .    .
 B    2    4    3
 B    3    5    1

I want to produce a new column called 'id' with a unique number for every name, such as:

name id year var1 var2
 A    1  1    4    3
 A    1  2    5    1
 A    1  3    4    2
 B    2  1    .    .
 B    2  2    4    3
 B    2  3    5    1

Any help?

like image 421
user1172558 Avatar asked Feb 15 '12 07:02

user1172558


People also ask

How do I create a column of numbers in R?

To add a new column to a dataframe in R you can use the $-operator. For example, to add the column “NewColumn”, you can do like this: dataf$NewColumn <- Values . Now, this will effectively add your new variable to your dataset.


1 Answers

If your name column doesn't just contain single letters (or even if it does), you can use:

dat$id <- as.numeric(as.factor(dat$name))

or, more simply:

dat$id <- c(as.factor(dat$name))

where dat is your data.frame.

like image 104
jbaums Avatar answered Nov 12 '22 01:11

jbaums