Search code examples
rdataframemultiplicationcalculation

Multiply cell values with first column


I have a data frame that looks like the following

sample_data <- data.frame(Cohort = c("Q1", "Q2", "Q3", "Q4"),
                      Cohort.Size = c(120, 234, 345, 222),
                      MO1 = c(8.3, 7.1, 2.4, 5.4),
                      MO2 = c(6.6, 3.2, 5.3, NA),
                      MO3 = c(2.3, 4.5, NA, NA),
                      MO4 = c(4.5, NA, NA, NA))

As you can see, the second column Cohort.Size consists of absolute numbers whereas all remaining columns MO1, MO2, MO3, MO4 show percentages. Is there an easy solution how I could multiply the percentage values with the corresponding value in the first column in order to get absolute numbers?

The result I am looking for would be the following table:

Cohort | Cohort.Size |  MO1 | MO2  | MO3  | MO4
Q1     | 120         | 9.96 | 7.92 | 2.76 | 5.4
Q2     | 234         | 16.6 | 7.49 | 10.53| 
Q3     | 345         | 8.28 | 18.29|      | 
Q4     | 222         | 11.99|      |      | 

Thank you!


Solution

  • You can perform this calculation directly on the dataframe.

    cols <- grep('MO', names(sample_data))
    sample_data[cols] <- sample_data$Cohort.Size * sample_data[cols]/100
    sample_data
    
    #  Cohort Cohort.Size    MO1    MO2   MO3 MO4
    #1     Q1         120  9.960  7.920  2.76 5.4
    #2     Q2         234 16.614  7.488 10.53  NA
    #3     Q3         345  8.280 18.285    NA  NA
    #4     Q4         222 11.988     NA    NA  NA