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?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With