Categories
Uncategorized

Extracting data from a Data Frame 101 – R

# All info goes in - Name, Age, Height, and Weight
# Age, Height, and Weight are integers, therefore no quotes.
names <- c("joe","jack","jim","james")
age <- c(23,25,27,23)
height <- c(170,173,168,172)
weight <- c(65,73,71,70)

# Place all info into a data frame called dfD
dfD <- data.frame(names,age,height,weight)

# Returns
  names age height weight
1   joe  23    170     65
2  jack  25    173     73
3   jim  27    168     71
4 james  23    172     70

# Let's get all of Jim's data
dfD[(dfD[1]=="jim"),]

# Returns
  names age height weight
3   jim  27    168     71

# Now, a set of people
peeps <- c("joe","james")
subset(dfD, names %in% peeps)

# Returns
  names age height weight
1   joe  23    170     65
4 james  23    172     70

# Finally, people shorter than 173 cm
subset(dfD, height < 173)

# Returns
  names age height weight
1   joe  23    170     65
3   jim  27    168     71
4 james  23    172     70

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s