Can I use underscore to make numbers more readable in R?
# Countries
countries <- c("United States", "India", "China", "Russia", "Brazil", "Mexico")
# Population
populations <- c(326_000_000, 1_380_000_000, 1_440_000_000, 144_000_000, 208_000_000, 128_000_000)
Error: unexpected input in "populations <- c(326_"
I was supposed to work, but it doesn't, any idea?
CodePudding user response:
It's not supported like it is in JavaScript, but if it's very important to do for legibility, you could do something like below.
Note that the numbers are stored as character because R does not support numeric types with underscores.
numbers <- c("100_000_000", "20_000_000_000", "25_987_654_321")
read_nums <- function(input) {
as.numeric(gsub("_", "", input))
}
read_nums(numbers)
# output
[1] 100000000 20000000000 25987654321
CodePudding user response:
One aspect you may want to consider is how data are stored, and how they are printed in the console. For example, if you store these data in a tibble
, you will see that an underlining effect is used as a sort of separator when printing the data to the console.
You may also want to consider format
or prettyNum
for customising output, but keep in mind that using them will convert the vector from numeric to character.
populations <- c(326000000, 1380000000, 1440000000, 144000000, 208000000, 128000000)
countries <- c("United States", "India", "China", "Russia", "Brazil", "Mexico")
format(populations, big.mark = "_", scientific = FALSE)
#> [1] " 326_000_000" "1_380_000_000" "1_440_000_000" " 144_000_000"
#> [5] " 208_000_000" " 128_000_000"
prettyNum(populations, big.mark="_", scientific=FALSE)
#> [1] "326_000_000" "1_380_000_000" "1_440_000_000" "144_000_000"
#> [5] "208_000_000" "128_000_000"
tibble::tibble(countries = countries,
populations = populations)
#> # A tibble: 6 × 2
#> countries populations
#> <chr> <dbl>
#> 1 United States 326000000
#> 2 India 1380000000
#> 3 China 1440000000
#> 4 Russia 144000000
#> 5 Brazil 208000000
#> 6 Mexico 128000000
Created on 2022-12-09 with reprex v2.0.2