Romano Vacca
Romano Vacca

Reputation: 315

Selection of data frame elements

I am doing a "introduction to r " from edx and fail to understand something. This is my dataframe called planets_df:

      name               type diameter rotation has_rings
    1 Mercury Terrestrial planet    0.382    58.64     FALSE
    2   Venus Terrestrial planet    0.949  -243.02     FALSE
    3   Earth Terrestrial planet    1.000     1.00     FALSE
    4    Mars Terrestrial planet    0.532     1.03     FALSE
    5 Jupiter          Gas giant   11.209     0.41      TRUE
    6  Saturn          Gas giant    9.449     0.43      TRUE
    7  Uranus          Gas giant    4.007    -0.72      TRUE
    8 Neptune          Gas giant    3.883     0.67      TRUE

and i want to select the elements from diameter and rotation column for the third row "Earth". I know i can do this by

earth_data <- planets_df[3,c("diameter", "rotation")]

However, i thought i could also select that row by :

earth_data <- planets_df[c("name"["Earth"]),c("diameter", "rotation")]

but that gives me :

diameter rotation
NA       NA       NA

But i do not understand why this is, i thought since you can select columns by their name, you could also select rows in the same way. Can someone explain me why this is?

Upvotes: 0

Views: 90

Answers (1)

DeveauP
DeveauP

Reputation: 1237

The issue in your code is here:

earth_data <- planets_df[c("name"["Earth"]),c("diameter", "rotation")]

What you want is to get all rows that have "Earth" in the "name" column. This is achieved by:

planets_df[planets_df[,"name"] =="Earth",]

So the full line would be:

earth_data <- planets_df[planets_df[,"name"]=="Earth",c("diameter", "rotation")]

Upvotes: 1

Related Questions