2
$\begingroup$

Or more specifically, why would the index of a dataframe not be in ascending numerical order?

When I display the dataframe, the first row has column names, the data begins on second row, but the leftmost column (which doesn't have a header), is not in order, instead it shows as:

2
1
4
6
5
3

$\endgroup$

2 Answers 2

5
$\begingroup$

Data frames have rownames attribute which is shown as the captionless leftmost column; you've propably altered the order of rows in data frame and it just shows the original indices. Try

 rownames(df)<-NULL  

to recreate it to 1:N.

$\endgroup$
5
$\begingroup$

If you reorder a data frame the row.names with be reordered to match. Note that if you haven't supplied rownames, R makes them up for you as characters as.character(1:nrow(obj)), where obj is your data frame. Hence these are row names.

> df <- data.frame(A = 5:1, B = LETTERS[1:5])
> df
  A B
1 5 A
2 4 B
3 3 C
4 2 D
5 1 E
> df[order(df$A),]
  A B
5 1 E
4 2 D
3 3 C
2 4 B
1 5 A
> df[sample(5),]
  A B
3 3 C
2 4 B
4 2 D
1 5 A
5 1 E

But I could just as well have applied some rownames:

> rownames(df) <- letters[1:5]
> df
  A B
a 5 A
b 4 B
c 3 C
d 2 D
e 1 E
> df[sample(5),]
  A B
d 2 D
c 3 C
a 5 A
b 4 B
e 1 E

You would need to show us how your data were read in, example data, and what code you are using if the above doesn't answer your Q.

If the rownames are not important, ignore them or do:

rownames(df) <- NULL
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.