I would like to convert the dot (decimal separator) to comma as decimal separator.
I tried using format(decimal.mark=",")
but got an error.
df<-structure(list(ponto = c("F01", "F02", "F03", "F04", "F05", "F06"
), `Vegetação Nativa` = c(0.09, 3.12, 8.22, 5.92, 1.95, 4.7),
Agricultura = c(91.78, 91.87, 100, 100, 91.5, 99.38), Pastagem = c(-16.99,
-33.16, -22.73, -24.12, -38, -47.3), `Área Urbana` = c(27.32,
27.32, 27.57, 27.57, 19.18, NaN), `Solo Exposto` = c(10.04,
2.13, 8.5, 6.64, -29.35, -442.86), `Corpo Hídrico` = c(-15.62,
-15.62, NaN, NaN, -17.11, -25.93)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L), groups = structure(list(
ponto = c("F01", "F02", "F03", "F04", "F05", "F06"), .rows = structure(list(
1L, 2L, 3L, 4L, 5L, 6L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), .drop = TRUE))
I tried this, but got an error:
df%>%
format(decimal.mark=",")
CodePudding user response:
One way is to use mutate
and across
from dplyr
. Though this will still change their type to character
.
library(dplyr)
df %>%
mutate(across(everything(), format, decimal.mark = ","))
Output
# A tibble: 6 × 7
# Groups: ponto [6]
ponto `Vegetação Nativa` Agricultura Pastagem `Área Urbana` `Solo Exposto` `Corpo Hídrico`
<chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 F01 0,09 91,78 -16,99 27,32 10,04 -15,62
2 F02 3,12 91,87 -33,16 27,32 2,13 -15,62
3 F03 8,22 100 -22,73 27,57 8,5 NaN
4 F04 5,92 100 -24,12 27,57 6,64 NaN
5 F05 1,95 91,5 -38 19,18 -29,35 -17,11
6 F06 4,7 99,38 -47,3 NaN -442,86 -25,93
Additionally, if you are wanting to simply change how you are seeing the data while printing, plotting, etc. for anything that is as.character
, then you can change the default options. You can also read more about it here (this post has a lot of discussion directly related to your question).
options(OutDec= ",")
Examples (after changing options):
c(1.5, 3.456, 40000.89)
# [1] 1,500 3,456 40000,890
However, the caveat is that the data must be character. So with your data, we could convert those to character, then they will display with the comma rather than period.
df %>% mutate(across(everything(), as.character))
# A tibble: 6 × 7
# Groups: ponto [6]
ponto `Vegetação Nativa` Agricultura Pastagem `Área Urbana` `Solo Exposto` `Corpo Hídrico`
<chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 F01 0,09 91,78 -16,99 27,32 10,04 -15,62
2 F02 3,12 91,87 -33,16 27,32 2,13 -15,62
3 F03 8,22 100 -22,73 27,57 8,5 NaN
4 F04 5,92 100 -24,12 27,57 6,64 NaN
5 F05 1,95 91,5 -38 19,18 -29,35 -17,11
6 F06 4,7 99,38 -47,3 NaN -442,86 -25,93