Search code examples
rdataframesubtraction

R: Subtracting two dataframes except some of the columns


I have two dataframes including stock returns for different types of stocks. I want to subtract the dataframes but without subtracting the three first columns in the dataframes (Year, Quarter, Group). In other words, I only want the two last columns which include the returns to be subtracted.

Below is my current syntax. In the first two lines, I create new dataframes, which are the ones to be subtracted later in line 3. Then at the end, I merge them into a new dataframe containing both subtracted, high and low returns values.

BMH <- subset(Ret_BM, BM_gr=="H")
BML <- subset (Ret_BM, BM_gr == "L")
BM_HML <- BMH - BML  #This is wrong since it subtracts year, quarter and group column as well.

plot_data <- join_all(list(BMH, BML, BM_HML), by = c("year_ret", "Q"))

Solution

  • If you want to keep Variables as Year, Quarter, and Group you can do:

    cbind(BMH[ ,1:3], BMH[,-c(1:3)] - BML[,-c(1:3)])
    

    and save convert it again to a data frame with as.data.frame()