Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting the number of decimals in a dataframe (R)

Tags:

I would like to limit the number of decimals when a data frame is imported. My .txt input have 16 decimals to each row in collumn "Value". My dataframe look like that:

Value   0.202021561664556 0.202021561664556 0.202021561664556 0.202021561664556 ... 

My expected dataframe

Value 0.20202156 0.20202156 0.20202156 0.20202156 ... 

Real input (DF) that not works:

DF <- "NE001358.Log.R.Ratio     -0.0970369274475688     0.131893549586039     0.0629266495860389     0.299559132381831     -0.0128804337656807     0.0639743960526874     0.0271669351886552     0.322395363972391     0.179591292893632"  DF <- read.table(text=DF, header = TRUE) 
like image 344
user3091668 Avatar asked Apr 22 '14 10:04

user3091668


People also ask

How do I truncate decimals in R?

Truncate function in R – trunc() trunc(x) is a truncate function in R, which rounds to the nearest integer in the direction of 0. trunc() function basically truncates the values in the decimal places. trunc() function is used in truncating the values of vector and truncating the values of a column in R.

How do you round to 2 decimal places in R?

You can use the following functions to round numbers in R: round(x, digits = 0): Rounds values to specified number of decimal places. signif(x, digits = 6): Rounds values to specified number of significant digits.


1 Answers

Here is.num is TRUE for numeric columns and FALSE otherwise. We then apply round to the numeric columns:

is.num <- sapply(DF, is.numeric) DF[is.num] <- lapply(DF[is.num], round, 8) 

If what you meant was not that you need to change the data frame but just that you want to display the data frame to 8 digits then it's just:

print(DF, digits = 8) 

In dplyr 1.0.0 and later one can use across within mutate like this:

library(dplyr) DF %>% mutate(across(where(is.numeric), ~ round(., 8))) 
like image 114
G. Grothendieck Avatar answered Oct 04 '22 14:10

G. Grothendieck