R将点(“。”)设置为千位分隔符,将逗号(“,”)设置为小数分隔符

时间:2018-02-20 08:43:09

标签: r decimal numeric separator format-conversion

我收到了从SQL数据库中提取的excel文件,这意味着数字字段显示为12345,67

我使用R 3.2.5导入library(readxl)中的文件,并正确显示数字字段为12345.67。

我在选项中将逗号设置为小数分隔符,因为我需要以该格式打印报告。 但是,我找不到设置“。”点,千万分隔符。 我尝试了formatformatc,结果是

"Warning message:
NAs introduced by coercion"

错误。 format和formatc导致字符串不是数字格式。

请使用此模拟数据框进行可重复的研究。

variable=c("a","b","c","d","e","f","g","h","i","j")
value=c(0.00,196036.95,196036.95, 10244.29,90470.73,33926.53,37142.59,6.65,15.40,180941.47)
df=data.frame(variable, value)
#View the data frame

print(df)

#a quick bar plot
plot=ggplot(data=df, aes(x=variable, y=value)) +  geom_bar(stat="identity")
plot

#set comma as decimal point. We need dot as thousands separator.
options(OutDec= ",")

print(df)  # here the numbers are correctly presented as extracted from the SQL database
plot

将结果转换为数字时格式化和格式化结果:

as.numeric(format(df$value, big.mark = "."))
 [1] NA NA NA NA NA NA NA NA NA NA
Warning message:
NAs introduced by coercion 

我需要以这种格式报告最终结果,但是以数字形式报告,因此我可以生成图表和表格:

 format(df$value, big.mark = ".")
 [1] "      0,00" "196.036,95" "196.036,95" " 10.244,29" " 90.470,73" " 33.926,53" " 37.142,59" "      6,65" "     15,40" "180.941,47"

编辑: 我的sessionInfo()

R version 3.2.5 (2016-04-14)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=Greek_Greece.1253  LC_CTYPE=Greek_Greece.1253    LC_MONETARY=Greek_Greece.1253 LC_NUMERIC=C                  LC_TIME=Greek_Greece.1253    

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] pander_0.6.0   scales_0.4.1   forcats_0.2.0  png_0.1-7      gtable_0.2.0   cowplot_0.6.3  ggpubr_0.1.0   zoo_1.8-0      gtools_3.5.0   reshape2_1.4.2
[11] gridExtra_2.3  gridBase_0.4-7 ggplot2_2.2.1  readxl_0.1.1  

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.10     magrittr_1.5     munsell_0.4.3    colorspace_1.3-2 lattice_0.20-33  stringr_1.2.0    plyr_1.8.4       tools_3.2.5      yaml_2.1.14     
[10] lazyeval_0.2.0   digest_0.6.12    tibble_1.3.0     labeling_0.3     stringi_1.1.5   

1 个答案:

答案 0 :(得分:1)

你很接近,你只需要在scale_y_continuous中指定:

plot + scale_y_continuous(label = function(x) format(x, big.mark = ".", decimal.mark = ","))