Search code examples
rfunctiondataframenumericnamed

Multiply rows of R dataframe by matching named numeric


How can you selectively multiple a row in a dataframe by the corresponding number in a named numeric?

## Create DataFrame
d <- data.frame(a=c(1,1,2), b=c(2,2,1), c=c(3,0,1))
rownames(d) = c("X", "Y", "Z")

## Create Named Numeric
named_numeric = c(2,1,3)
names(named_numeric) = c("X", "Y", "Z")
named_numeric

All values in the first row of the dataframe ("X": 1,2,3) would by multiplied by the value of "X" in the named numeric (2) in this case. The result of the first row would be "X": 2,4,6.

expected_output = data.frame(a=c(2,1,6), b=c(4,2,3), c=c(6,0,3))
rownames(expected_output) = c("X", "Y", "Z")

Solution

  • We can just do

    out <- d * named_numeric
    identical(expected_output, out)
    #[1] TRUE
    

    if the names of named_numeric is not aligned with the row names, then reorder one of them and multiply

    d * named_numeric[row.names(d)]