R:将名称添加为索引而不是数字

时间:2018-02-28 03:44:01

标签: r machine-learning

我有一个带有一些值的向量,我想用名称替换向量索引。所以,我想用这样的名字替换[1,] [2,] [3,]

以下是没有名称的beta值:

 [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

我正在尝试添加这样的名字:

(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

这就是我到现在所做的:

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 

我试过这个rownames(beta[,-1])=colnames(x)但是我收到一个错误: dimnamesGets(x,value)中的错误:   为“dgCMatrix”对象提供的无效dimnames

1 个答案:

答案 0 :(得分:0)

只需使用as.data.frame.matrixbeta转换为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

要将rownames转换为列,您可以使用tibble::rownames_to_column

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