简体   繁体   中英

How to convert a 'string numeric' column into pure numeric in R matrix

Giving the following data:

      GOBPID                    Term     col1 col2 col3 col4 col5
1 GO:0001659 temperature_homeostasis 3.496906    0    0    0    0
2 GO:0001660        fever_generation 3.226069    0    0    0    0

I tried to create a matrix where col1-5 (could be more than 5) into numeric.

Currently it looks like this:

> dat <- read.table("http://dpaste.com/1486837/plain/",header=TRUE)
> as.matrix(as.numeric(dat))

    GOBPID       Term                      col1       col2 col3 col4 col5
[1,] "GO:0001659" "temperature_homeostasis" "3.496906" "0"  "0"  "0"  "0" 
[2,] "GO:0001660" "fever_generation"        "3.226069" "0"  "0"  "0"  "0" 

What's the way to do it?

I intend to have this:

          GOBPID                      Term      col1 col2 col3 col4 col5
[1,] "GO:0001659" "temperature_homeostasis" 3.496906    0    0    0    0 
[2,] "GO:0001660" "fever_generation"        3.226069    0    0    0    0

With this command I failed: as.numeric(as.matrix(dat))

dat is a data.frame , not a matrix . The columns of a data.frame can have different types. In your example, the type of col1-5 is already numeric. Try it yourself:

> dat <- read.table("http://dpaste.com/1486837/plain/",header=TRUE)
> sapply(dat, class)
   GOBPID      Term      col1      col2      col3      col4      col5 
 "factor"  "factor" "numeric" "integer" "integer" "integer" "integer" 
> dat[,3] + 1
[1] 4.496906 4.226069
> dat[,4] + 1
[1] 1 1

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