Search code examples
rdataframemultiplication

Multiply values in several columns by the values in one column


I have the following data:

ID <- c("CB1", "CB2","CB3")
size <- c(10, 40, 4)
Year.1 <- c(10, 6, 15)
Year.2 <- c(12, 7, 20)
Year.3 <- c(14, 8, 25)
data <- data.frame(ID, size, Year.1, Year.2, Year.3)

I want to multiply the values for all years, by the values in the 'size' column (I have ten years in my actual data frame). The data should end up looking like this.

ID <- c("CB1", "CB2","CB3")
size <- c(10, 40, 4)
Year.1 <- c(100, 240, 60)
Year.2 <- c(120, 280, 80)
Year.3 <- c(140, 320, 100)
data <- data.frame(ID, size, Year.1, Year.2, Year.3)

Ideally, the new values will replace the existing values for each year, as I don't really want to add another ten columns to my data frame.


Solution

  • lapply is a good tool here. You can pass it the vectors you want to multiply, an anonymous function that does the multiplication, and an additional argument for the values to multiply by.

    ID <- c("CB1", "CB2","CB3")
    size <- c(10, 40, 4)
    Year.1 <- c(10, 6, 15)
    Year.2 <- c(12, 7, 20)
    Year.3 <- c(14, 8, 25)
    df <- data.frame(ID, size, Year.1, Year.2, Year.3)
    
    df[, paste0("Year.", 1:3)] <- 
      lapply(df[, paste0("Year.", 1:3)],
             function(x, y) x * y,
             y = df$size)
    
    df
       ID size Year.1 Year.2 Year.3
    1 CB1   10    100    120    140
    2 CB2   40    240    280    320
    3 CB3    4     60     80    100