Remove decimals from a column in a data frame

22,327

Solution 1

One option would be to convert to integer class by looping over the columns (with lapply)

exprs[] <- lapply(exprs, as.integer)
exprs
#                  v1 v2 v3 v4 v5 v6
#ENSG00000226823.1 15 14 22 13  5 16
#ENSG00000266470.1  0  0  0  0  0  0
#ENSG00000229435.2  0  0  0  0  0  0
#ENSG00000277456.1  0  0  0  0  0  0
#ENSG00000236077.2  0  0  0  0  0  0
#ENSG00000280518.1  0 57 30 23  4  0

data

exprs <- structure(list(v1 = c(15L, 0L, 0L, 0L, 0L, 0L), v2 = c(14.4947, 
0, 0, 0, 0, 57.9833), v3 = c(22.5606, 0, 0, 0, 0, 30.4089), 
v4 = c(13.5819, 
0, 0, 0, 0, 23.0059), v5 = c(5.09327, 0, 0, 0, 0, 4.85613), v6 = c(16.8503, 
0, 0, 0, 0, 0)), .Names = c("v1", "v2", "v3", "v4", "v5", "v6"
), class = "data.frame", row.names = c("ENSG00000226823.1", "ENSG00000266470.1", 
"ENSG00000229435.2", "ENSG00000277456.1", "ENSG00000236077.2", 
"ENSG00000280518.1"))

Solution 2

Be VERY careful with converting to integer as that will ROUND the value. I had this same problem with a look-up table that had all values as xxx.5 and I did NOT want to round - just drop the decimal. The answer from @Benjamin is the correct way to do this i.e. use floor().

Share:
22,327
Saad
Author by

Saad

Updated on January 10, 2021

Comments

  • Saad
    Saad over 3 years

    I have a data frame with numbers in the columns and those numbers are decimals. I want to remove the decimals and ant whole numbers in the columns.

    my data frame expsrs looks like this

    ENSG00000226823.1           15     14.4947     22.5606     13.5819     5.09327     16.8503
    ENSG00000266470.1            0           0           0           0           0           0
    ENSG00000229435.2            0           0           0           0           0           0
    ENSG00000277456.1            0           0           0           0           0           0
    ENSG00000236077.2            0           0           0           0           0           0
    ENSG00000280518.1            0     57.9833     30.4089     23.0059     4.85613           0
    

    I have tried this code but it removes the decimals but changes the value also.

    exprs$V1<-round(as.numeric(exprs$V1), 0)
    

    I want to remove decimals from all the columns but not from the rownames. Can anybody help?

  • Benjamin
    Benjamin over 7 years
    floor could be used as well.
  • umbe1987
    umbe1987 almost 2 years
    even trunc if you just want to preserve the integer part intact. Example x <- c(-3.2, -1.8, 2.3, 2.9); floor(x); trunc(x) (taken from quora.com/What-is-the-difference-between-floor-and-trunc-in-‌​R)