ProtocolWhisper
ProtocolWhisper

Reputation: 79

Indexing dataframes in R

good day I don´t understand a topic here, is like it works but I can´t understand why I have this database

enter image description here

# planets_df is pre-loaded in your workspace


# Use order() to create positions
positions <- order(planets_df$diameter)
positions
# Use positions to sort planets_df
planets_df[positions,]

I don´t understand why if u take the column diameter, then if u want to order it why u put it in a row of the dataframe like for me it should be [ rows, colum] but u put a column in a row and it changes, I really don´t get that.Why it´s not planets_df[,positions].

The exercise is solved I just don´t get it, is a data camp exercise btw.

Sorry if my English is wrong, it is not my native language.

Upvotes: 0

Views: 264

Answers (1)

mcz
mcz

Reputation: 587

I believe that I have created an example that matches your description. For the mtcars data set, which is pre-loaded in any R session, we can sort based on the variable mpg.

The function order returns the row indices sorted by mpg in this case. The ordering variable indicates the order that the rows should be presented in by storing the row indices based on mpg.

ordering <- order(mtcars$mpg)

This next step indicates that we want the rows of mtcars as specified by ordering. Essentially ordering is the order of the rows we want and so we pass that object to the row portion the call to mtcars.

mtcars[ordering,]

If we instead passed ordering as the columns, we would be reordering the columns of mtcars instead of the rows.

Upvotes: 3

Related Questions