Reset Sequence or Row Numbers in R Data Frame
In this tutorial, we will learn how to reorder or correct the order of row numbers when a Dataframe is filtered or a subset of a dataframe is accessed.
To reorder the row numbers of a filtered or subset Dataframe, assign row numbers of the dataframe with a sequence of numbers until the length of the filtered dataframe.
Example 1 – Reset Row Numbers in R Data Frame
Consider a Dataframe DF1 shown below.
> DF1 = data.frame(x = c(9, NA, 7, 4), y = c(4, NA, NA, 21))
> DF1
x y
1 9 4
2 NA NA
3 7 NA
4 4 21
In this original dataframe, the row numbers are ordered from 1 to 4.
Let us filter the rows of this dataframe that do not contain any NAs.
> resultDF = DF1[complete.cases(DF1), ]
> resultDF
x y
1 9 4
4 4 21
The second and third rows are trashed out and only rows numbered one and four got into the filtered output dataframe. But the row numbers are not in a sequence.
We need the rows of resultDF to be numbered in sequence without missing any numbers. We will set the rownames with a sequence of numbers with a length equal to number of rows in the dataframe.
> rownames(resultDF) = seq(length=nrow(resultDF))
> resultDF
x y
1 9 4
2 4 21
Viola! The numbers are sequenced.
Conclusion
In this R Tutorial, we have learned how to reset the sequence of row numbers of a dataframe obtained through filtering or subsetting.