Reputation: 261
So this is a quick question.
I have a dataframe of panel data, in which I have a column of identifications/names/IDs for each individual. Lets say there are n levels to this column, that is, n individuals in the panel over a certain timeframe.
I want to add a column N to the dataframe with this value n, that is a numbering of levels.
That is each ID/name/level gets assigned a number from 1 through n.
Here is a code that does what I want:
i = 1
for(l in levels(data$IDs)) {
data[data$ID == l,]$N = i
i = i+ 1
}
So far so good. Issue: My dataset is large. Very large. Far too much to do this manually. And the above operation takes too much time. This is a loop, so my guess is that there is a faster way to do this in R using vector operations. Anyone know a computationally quick way to do this?
Upvotes: 2
Views: 1275
Reputation: 132706
Just use data$N <- as.integer(data$ID)
. Factor variables are integers internally. Thus, it is easy to turn them into integer variables.
Upvotes: 3