Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

database - How to create ID column in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...