Rounding output from by function in R Rounding output from by function in R r r

Rounding output from by function in R


If you already have the output saved to a variable, say x:

x <- by(glaciers[,1:3],glaciers$activity.level,mean)

Then apply round() to each element (the output of by() in this case is a list).

x[] <- lapply(x,round,5)x

reassigning to x[] rather than x allows x to retain attributes attached to it from by().

Edit: round() actually changes the value of the variables but is decoupled from its printing. If you want to suppress the scientific notation output format, use format="f" argument to formatC()

> round(1.2345e10,5)[1] 1.2345e+10> formatC(1.2345e10,digits=5,format="f")[1] "12345000000.00000"

So the correction to the expression originally posted would be

x[] <- lapply(x,formatC,digits=5,format="f")


round() doesn't make sense in this instance, since you're working with very large numebrs. You want to use the format() command, and choose how many digits to display. For instance, to show 3 significant digits:

by(glaciers[,1:3], glaciers$activity.level, function(x) {      as.numeric(format(mean(x), digits=3))})


by(glaciers[,1:3], glaciers$activity.level, function(x){round(mean(x),5)})

UPDATE

Here is a working example:

glaciers <- as.data.frame(matrix(rnorm(1000),ncol=4)) glaciers[,4] <- sample(0:3,250,replace=TRUE) colnames(glaciers) <- c("A","B","C","activity.level") by(glaciers[,1:3], glaciers$activity.level, function(x){round(mean(x),5)})