Last active
February 15, 2017 20:34
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
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