Decimal number of decimal places in data frame (R)

I would like to limit the number of decimal places when importing a data frame. My .txt input has 16 decimal places for each row in the Value column. My dataframe looks like this:

Value 0.202021561664556 0.202021561664556 0.202021561664556 0.202021561664556 ... 

My expected data file

 Value 0.20202156 0.20202156 0.20202156 0.20202156 ... 

Real input (DF) that does not work:

 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) 
+7
decimal r limits maxlength
source share
2 answers

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

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

If you didn’t mean that you need to change the data frame, but simply so that you display a data frame of up to 8 digits, then it is simple:

 print(DF, digits = 8) 
+11
source share

just throw a copy of this into your project path in the utils directory and source it when you run the script

 "formatColumns" <- function(data, digits) { "%,%" <- function(x,y)paste(x,y,sep="") nms <- names(data) nc <- ncol(data) nd <- length(digits) if(nc!=nd) stop("Argument 'digits' must be vector of length " %,% nc %,% ", the number of columns in 'data'.") out <- as.data.frame(sapply(1:nc, FUN=function(x, d, Y) format(Y[,x], digits=d[x]), Y=tbl, d=digits)) if(!is.null(nms)) names(out) <- nms out } 

Now you can relax and unwind.

 formatColumns(MyData, digits=c(0,2,4,4,4,0,0)) 

et cetera et cetera et cetera

0
source share

All Articles