简体   繁体   中英

changing data frame from character to numeric

I have a large data frame with names columns and rows. For some reason the numbers in the data frame are listed as characters when I check with the below sapply function. I have tried to change to numeric as below but it changes the data frame - removes the names from the rows and is no longer a data frame. I cannot list the columns to change by hand as >100 columns and ensembl gene ID names as column names and DE1 etc as row names. Data frame is samples. sample of data looks like this:

     EN00000345    EN00000456    EN00000067
DE1   1.47           7.2          -1.23
DR16  3.4            6.5           0.2
C20   2.7            8.7           7.8 
DR12  4.5            3.2           12.1 
`````````
sapply(samples, mode)

fwrite(samples, "some.name.temp")
  samples<- fread("some.name.temp", colClasses = "numeric")


also tried

samples <- lapply(samples, function(x) as.numeric(as.character(x)))

return data is no longer a data frame and looks like:

    EN00000345    EN00000456    EN00000067
1     1.47           7.2          -1.23
2     3.4            6.5          0.2
3     2.7            8.7          7.8

You can try with this code (df=name of your dataframe) :

for(j in 1:ncol(df)){
  df[,j]=as.numeric(df[,j])
}

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