简体   繁体   中英

Naming a nameless first column of a matrix

I have a matrix with regression outputs and wanted to name the first column using a similar answer provided here and using the following code:

df1<-setNames(cbind(rownames(df), df, row.names = NULL), 
        c("pollutant", "Estimate" ,  "Std. Error" ,"t value" ,   "Pr(>|t|)" ))

However, that did not produce what I wanted. Usually I save the data as a csv file and re-import it and in these situations the first column is automatically named "X".

What is the wrong with the code above and how can I name the first column of this matrix and avoid the long process of saving and importing a file?

Sample data provided below:

> dput(mydf)
structure(c(3.14803244479112, 0.00216192812492776, 0.000684290073147021, 
0.0292623173688936, 0.0297132981713028, 0.00974078727655406, 
0.00560338111861983, 0.0204778865914662, 0.0222708214105165, 
0.0374599288412558, 0.0423851703062228, 0.00310423463278227, 
0.000395577034883573, 0.0115743985421555, 0.0116695497549973, 
0.0117671202864663, 0.0117449236915669, 0.0116767755856412, 0.011592495851043, 
0.0134646435665112, 74.2720253816921, 0.696444818344823, 1.72985288023209, 
2.52819334519339, 2.54622490114312, 0.827797034399079, 0.477089614693976, 
1.753727854173, 1.9211412017467, 2.78209583909259, 0, 0.486174360549084, 
0.0837024207196054, 0.0114878037421748, 0.0109115954666798, 0.407814812496389, 
0.633313804135875, 0.0795226758181369, 0.0547561105194828, 0.00541595385956953
), .Dim = c(10L, 4L), .Dimnames = list(c("(Intercept)", "o3t_01", 
"rh_01", "as.factor(dow)2", "as.factor(dow)3", "as.factor(dow)4", 
"as.factor(dow)5", "as.factor(dow)6", "as.factor(dow)7", "as.factor(holiday)1"
), c("Estimate", "Std. Error", "t value", "Pr(>|t|)")))

You have to use data.frame instead of cbind to allocate different types of data into one structure.

> data.frame(pollutant=rownames(df), df, row.names=NULL, check.names = FALSE)
             pollutant     Estimate  Std. Error    t value    Pr(>|t|)
1          (Intercept) 3.1480324448 0.042385170 74.2720254 0.000000000
2               o3t_01 0.0021619281 0.003104235  0.6964448 0.486174361
3                rh_01 0.0006842901 0.000395577  1.7298529 0.083702421
4      as.factor(dow)2 0.0292623174 0.011574399  2.5281933 0.011487804
5      as.factor(dow)3 0.0297132982 0.011669550  2.5462249 0.010911595
6      as.factor(dow)4 0.0097407873 0.011767120  0.8277970 0.407814812
7      as.factor(dow)5 0.0056033811 0.011744924  0.4770896 0.633313804
8      as.factor(dow)6 0.0204778866 0.011676776  1.7537279 0.079522676
9      as.factor(dow)7 0.0222708214 0.011592496  1.9211412 0.054756111
10 as.factor(holiday)1 0.0374599288 0.013464644  2.7820958 0.005415954

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM