Jeffrey
Jeffrey

Reputation: 110

How to keep/assign row & column names when combining 2 vectors into a matrix in R

Hello, I'm fairly new to R programming so please don't judge if this seems pretty straightforward.

I was wondering if there is a way to do the following: I want to combine 2 vectors into an array but keep/assign their column and row names.

My code:

library(ISLR)

mean = sapply(Auto[, 1:3], mean)
sd = sapply(Auto[, 1:3], sd)

mean_sd = matrix(
   data = c(mean, sd),
   nrow = 2, ncol = 3, byrow = TRUE
)

Printing these individually prints them with their column names as intended.

mean
 mpg           cylinders        weight  
 23.445918     104.469388       2977.584184 
sd
 mpg           cylinders        weight 
 7.805007      1.705783         849.402560   

but printing them combined I get indices and not names.

mean_sd
          [,1]     [,2]      [,3]
[1,] 23.445918 5.471939 2977.5842
[2,]  7.805007 1.705783  849.4026

Is there a way to get the following:

mean_sd
              mpg   cylinders       weight
mean    23.445918    5.471939    2977.5842
sd       7.805007    1.705783     849.4026

I searched around a bit and found that I should be using dimnames(data) but I couldn't understand how to apply it to my code.

Upvotes: 0

Views: 399

Answers (1)

MKR
MKR

Reputation: 1700

You just need to use data.frame() instead of matrix()

mean_sd = data.frame(
  mean = sapply(mtcars[, 1:3], mean),
  sd = sapply(mtcars[, 1:3], sd)
)

Upvotes: 1

Related Questions