简体   繁体   中英

Error when converting dataframe row to character vector

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?

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.

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