Dropping columns in a data frame that are not in another data frame

I am facing a problem matching the data in two data frames. I have one data frame with stock prices and another with company revenues. However, the companies in both data frames are not all the same. Here is a reproducible example of what I am dealing with:

AAPL <- c(50,55,75,40,60)
MSFT <- c(80,65,70,75,80)
GE <- c(20,25,30,25,35)
Prices <- data.frame(AAPL,MSFT,GE)

AAPL <- c(100,110,120,110,100)
MSFT <- c(200,185,195,170,180)
PFE <- c(80,70,80,75,75)
Revenues <- data.frame(AAPL,MSFT,PFE)

I would like to have a new data frame for the ratio Price/Revenues for companies in both data frames. It would look like this.

AAPL.ps <- c(0.5,0.5,0.625,0.364, 0.6)
MSFT.ps <- c(0.4,0.351,0.359,0.441,0.444)
price.sales <- data.frame (AAPL.ps,MSFT.ps)

I am new in R and have been struggling with this for a while.

Any insight on how I can do this?

Thank you in advance

Upvotes: 1

Views: 44

Answers (1)

Andrew Gustar
Andrew Gustar

Reputation: 18425

You could do it like this...

common <- intersect(names(Prices),names(Revenues)) #common column names

price.sales <- Prices[,common]/Revenues[,common] #just use those columns

price.sales
       AAPL      MSFT
1 0.5000000 0.4000000
2 0.5000000 0.3513514
3 0.6250000 0.3589744
4 0.3636364 0.4411765
5 0.6000000 0.4444444

Upvotes: 3

Related Questions