R How to Create an Index ID Column in a Data Frame (Example Code)
This page illustrates how to append an index ID to a data frame in R.
Creation of Example Data
data(iris) # Load example data head(iris) # Head of example data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Load example data head(iris) # Head of example data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
Example: Creating ID Column in Data Frame
iris_new <- cbind(ID = 1:nrow(iris), iris) # Append index ID head(iris_new) # Show head of new iris data # ID Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 1 5.1 3.5 1.4 0.2 setosa # 2 2 4.9 3.0 1.4 0.2 setosa # 3 3 4.7 3.2 1.3 0.2 setosa # 4 4 4.6 3.1 1.5 0.2 setosa # 5 5 5.0 3.6 1.4 0.2 setosa # 6 6 5.4 3.9 1.7 0.4 setosa |
iris_new <- cbind(ID = 1:nrow(iris), iris) # Append index ID head(iris_new) # Show head of new iris data # ID Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 1 5.1 3.5 1.4 0.2 setosa # 2 2 4.9 3.0 1.4 0.2 setosa # 3 3 4.7 3.2 1.3 0.2 setosa # 4 4 4.6 3.1 1.5 0.2 setosa # 5 5 5.0 3.6 1.4 0.2 setosa # 6 6 5.4 3.9 1.7 0.4 setosa
Related Articles
Please have a look at the following R programming tutorials. They discuss topics such as loops, extracting data, variables, and indices.