Divide Each Row of Matrix & Data Frame by Vector Element in R (Example) | t & as.data.frame Function

preview_player
Показать описание
R code of this video:

mat <- matrix(1:20, ncol = 4) # Create example matrix
mat # Print example matrix

vec <- c(5, 1, 8, 3) # Create example vector
vec # Print example vector

mat_div <- t(t(mat) / vec) # Divide rows of matrix by vector
mat_div # Print divided matrix

data # Print example data frame

data_div # Print divided data frame

Follow me on Social Media:

Рекомендации по теме
Комментарии
Автор

I will recommend you the following code (online with R )
mat_div = sapply(1:ncol(mat), function(x) mat[, x]/vec[x])
data = as.data.frame(mat)
data_div = as.data.frame(sapply(1:ncol(mat), function(x) data[, x]/vec[x]))

WahranRai
Автор

Very nice video but we can generate the same result for the data frame just by dividing into the data frame with the vector directly. Or simply: df/vec - no need to transpose twice (you forgot to mention what the t stands for) or do another as.data.frame().

haraldurkarlsson
Автор

Joachim,
You might look into the flextable package. It prints out some nice looking table (it works with the tidyverse). For instance the function qflextable(df) will make a quick table.

haraldurkarlsson
welcome to shbcf.ru