Error when converting dataframe row to character vector

ぐ巨炮叔叔 提交于 2019-12-19 21:27:44

问题


So I've got the following dataframe, datafr.

          X1            X2               X1.1          X2.1              
      Composite       Element          Composite       Element          
14-3-3_epsilon-M-C -0.8660101895 14-3-3_epsilon-M-C -0.6814387425          
4E-BP1_pS65-R-V  0.1056560215    4E-BP1_pS65-R-V  0.1787506005    
4E-BP1_pT37T46-R-V  0.6408257495 4E-BP1_pT37T46-R-V -0.7485933875 
4E-BP1_pT70-R-C  0.6413568085    4E-BP1_pT70-R-C  0.9554481415    

I want to make the second row the column names, so I look at the row

datafr[1,]

and everything is as it should be

        X1      X2      X1.1      X2.1   
 Composite    Element   Composite Element

However, when I convert this to a character vector I get the words changing to numbers...

as.character(c(datafr[1,]))
[1] "49"  "161" "49"  "161" 

What is going on?


回答1:


The problem is that your data.frame columns are not characters but factors (read about the difference in the R introduction.)

You would have to do:

as.character(unlist(datafr[1, ]))

to get a character vector out ot your current data. However, you might want to fix your problem upstream within your code:

You could try to make sure that your data.frame does not contain factors in the first place. Most often, this is done by adding stringsAsFactors = FALSE to functions like data.frame, as.data.frame, read.table, read.csv where you might have used them. If you used read.table somewhere, I would highly suggest you also look at using header = TRUE to get the colnames where you wanted in the first place.



来源:https://stackoverflow.com/questions/22573664/error-when-converting-dataframe-row-to-character-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!