Skip to content

Instantly share code, notes, and snippets.

@Dulani
Last active February 15, 2017 20:34
Show Gist options
  • Save Dulani/e5f0d99e46430ef2a740363b70b2b684 to your computer and use it in GitHub Desktop.
Save Dulani/e5f0d99e46430ef2a740363b70b2b684 to your computer and use it in GitHub Desktop.
Multiply the columns of the data frame by the elements of the vector in R
---
title: "Multiply the columns of the data frame by the elements of the vector"
output: html_notebook
---
Matrix:
```{r}
(mat <- matrix(c(4:9),ncol = 2))
```
Vector:
```{r}
(vec <- c(3,4))
```
One quick way to multiply the columns of the data frame by the elements of the vector is to construct a diagonal matrix and then multiply the two together:
```{r}
(vec <- diag(vec))
```
And multiply:
```{r}
mat %*% vec
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment