from decimal import Decimal
'%g' % (Decimal(str(x)))
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 ()
не имеет смысла в этом случае, поскольку вы работаете с очень большими числами. Вы хотите использовать команду format () и выбрать, сколько цифр отображать. Например, чтобы показать 3 значащих цифры:
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)})
ОБНОВЛЕНИЕ
Вот рабочий пример:
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)})
Вы спросили " Как я могу округлить результат до 5 знаков после запятой? " но я думаю, что вы имели в виду: «Как я могу получить в моем выводе, скажем, 6 значащих цифр?» Следующий код сочетает в себе два из предыдущих ответов - идею переназначения res [] и использование signif вместо round.
glaciers <- data.frame(aspect=runif(20)*100,
sun.duration=runif(20)*10000,
latitude=runif(20)*10^9,
activity.level=sample(c('Active','Inactive','Relict'),20,replace=TRUE))
res <- by(glaciers[,1:3],glaciers$activity.level,mean)
res[] <- lapply(res,signif,3)
res
Этот код дает следующий результат:
glaciers$activity.level: Active
aspect sun.duration latitude
3.66e+01 4.72e+03 4.56e+08
-------------------------------------------------
glaciers$activity.level: Inactive
aspect sun.duration latitude
5.81e+01 5.28e+03 4.83e+08
-------------------------------------------------
glaciers$activity.level: Relict
aspect sun.duration latitude
6.08e+01 4.75e+03 3.98e+08
Do you want to round or to just truncate the number of digits shown? If the latter, use options(digits=3) or whatever.
> by(mpg[,8:9], mpg$cyl, mean)
mpg$cyl: 4
cty hwy
21.012 28.802
------------------------------------------------------------
mpg$cyl: 5
cty hwy
20.50 28.75
------------------------------------------------------------
mpg$cyl: 6
cty hwy
16.215 22.823
------------------------------------------------------------
mpg$cyl: 8
cty hwy
12.571 17.629
> options(digits=3)
> by(mpg[,8:9], mpg$cyl, mean)
mpg$cyl: 4
cty hwy
21.0 28.8
------------------------------------------------------------
mpg$cyl: 5
cty hwy
20.5 28.8
------------------------------------------------------------
mpg$cyl: 6
cty hwy
16.2 22.8
------------------------------------------------------------
mpg$cyl: 8
cty hwy
12.6 17.6
У вас есть всего пара минут, но вы можете попробовать посмотреть на format ()
, formatC ()
и prettyNum ( )
функций. Их справочные файлы сейчас кажутся мне чушью, но я не спал много. Однако несколько месяцев назад я использовал одну из этих функций - скорее всего formatC ()
- для отчета Sweave, в котором мне нужны были числа в очень специфическом формате.