How to extract data from a dataframe based on a variable in a certain column in R

Viewed 61

If I have a data frame of option prices such as

mydata = read.csv("optionprices.csv")
print(mydata)

Symbol Price Volume
AAPL   100   20
AAPL   105   40
AMZN   300   30
AMZN   305   60

How can I can around extracting data to create another data frame where mydata$Symbol == "AAPL"? So that my new data frame is

Symbol Price Volume
AAPL   100   20
AAPL   105   40
2 Answers

You can use the following code:

library(dplyr)

mydata %>% 
  filter(Symbol == "AAPL") -> df_new

df_new

  Symbol Price Volume
1   AAPL   100     20
2   AAPL   105     40

Or using base R:

df_new <- subset(mydata, Symbol == "AAPL")
df_new

  Symbol Price Volume
1   AAPL   100     20
2   AAPL   105     40

The answer by Anoushiravan is great.

Antoher method using base r: df[which(df$Symbol == "AAPL"),]

df <- data.frame(Symbol = c("AAPL","AAPL","AMZN","AMZN"), 
                 Price=c("100","105","300","305"),
                 Volume=c("20","40","30","60"))

> df 
  Symbol Price Volume
1   AAPL   100     20
2   AAPL   105     40
3   AMZN   300     30
4   AMZN   305     60

new_df <- df[which(df$Symbol == "AAPL"),]

> new_df
  Symbol Price Volume
1   AAPL   100     20
2   AAPL   105     40
Related