Skip to content

Instantly share code, notes, and snippets.

@pH-7
Last active April 25, 2024 23:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pH-7/1b89dbc5442b93e34cce597f4ec5d6af to your computer and use it in GitHub Desktop.
Save pH-7/1b89dbc5442b93e34cce597f4ec5d6af to your computer and use it in GitHub Desktop.
Data Frames, object structure in R
# create a data frame
user_df <- data.frame(
name = c("Alice", "Bob", "Charlie", "Dave"),
age = c(25, 32, 47, 19),
city = c("New York", "San Francisco", "Los Angeles", "Chicago"),
stringsAsFactors = FALSE
)
# view the data frame
user_df
# access to the 3rd age (Charlie's age)
user_df$age[3] # show: 47
# show all elements of 3rd user (Charlie)
user_df[3,] # show: Charlies, 47, Los Angeles
# Note: the below pH information is made up as for this example and doesn't reflect to the reality
my.database <- data.frame(
Cities = c("London", "Paris", "Berlin", "Amsterdam"),
Season=c("Winter", "Summer", "Spring", "Autumn"),
pH = c(7.4, 6.3, 3.4, 5.7)
)
my.database
# filter pH greater than 6 and show the "Cities"
# output: "London" "Paris"
my.database[my.database$pH > 6, "Cities"]
# output: Cities Season pH
# London Winter 7.4
my.database[my.database$Season == "Winter",]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment