I'm trying to create a new column "ID" in a dataframe.
Each row must have a unique ID incremented by 5 each time. But it should not start at 0, but from a desired number (lets say N = max of another dataset's column)
What would be the easiest way of doing that? (loop? function?)
CodePudding user response:
You can use seq(first_value,step, length.out)
, so in your case, ID <- seq(N, by = 5, length.out = nrow(data))
with data
you actual data. Here's an example with the starting point to 10 (which you can replace with N):
library(dplyr)
iris %>%
mutate(ID = seq(10,by = 5,length.out = nrow(iris)))
Output:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species ID
1 5.1 3.5 1.4 0.2 setosa 10
2 4.9 3.0 1.4 0.2 setosa 15
3 4.7 3.2 1.3 0.2 setosa 20
4 4.6 3.1 1.5 0.2 setosa 25
5 5.0 3.6 1.4 0.2 setosa 30
6 5.4 3.9 1.7 0.4 setosa 35
...