machine learning - R: Adding names as indexes, instead of numbers


Keywords:r 


Question: 

I've got a vector with some values, and I want to replace the vector indexing by names. So, I want to replace [1,] [2,] [3,] by some names like this:

Here are the beta values without names:

 [1,]  9.335256626
 [2,]  0.031369303
 [3,] -0.050801928
 [4,] -0.513624383
 [5,] -3.714115555
 [6,]  0.022378632
 [7,]  .          
 [8,] -0.599622031
 [9,]  0.494720259
[10,]  .          
[11,] -0.106661630
[12,] -0.007580542
[13,]  0.117596852
[14,] -0.125227171

And I am trying to add names like this:

(Intercept)  9.335256626
zn           0.031369303
indus       -0.050801928
chas        -0.513624383
nox         -3.714115555
rm           0.022378632
age          .          
dis         -0.599622031
rad          0.494720259
tax          .          
ptratio     -0.106661630
black       -0.007580542
lstat        0.117596852
medv        -0.125227171

This is what I did till now:

library(MASS)
library(glmnet)
Boston=na.omit(Boston)
x=model.matrix(crim~.,Boston)[,-1]
y=as.matrix(Boston$crim)
lasso.mod =glmnet(x,y, alpha =1, lambda = 0.1)
beta=coef(lasso.mod)
rownames(beta)=c() #Here I removed the names just to try to add them 

I tried this rownames(beta[,-1])=colnames(x) but I get an error: Error in dimnamesGets(x, value) : invalid dimnames given for “dgCMatrix” object


1 Answer: 

Just use as.data.frame.matrix to turn beta into a data.frame:

as.data.frame.matrix(beta)
#                      s0
#(Intercept)  9.335256626
#zn           0.031369303
#indus       -0.050801928
#chas        -0.513624383
#nox         -3.714115555
#rm           0.022378632
#age          0.000000000
#dis         -0.599622031
#rad          0.494720259
#tax          0.000000000
#ptratio     -0.106661630
#black       -0.007580542
#lstat        0.117596852
#medv        -0.125227171

To turn rownames into a column you can use tibble::rownames_to_column:

tibble::rownames_to_column(as.data.frame.matrix(beta))