Rachel
Rachel

Reputation: 13

Issue with R round adding extra zeros

I'm in the process of making 29 shiny apps that are all very similar but have data from different states. I've been successfully copying and pasting the code and just changing the data. I'm displaying outcomes of homeless and housed students and I want to round percentages to the nearest tenth. I'm having a problem where R is adding an extra 0 to the end of some percentages, but only for the homeless group and only with a certain handful of variables. It doesn't happen every time and even among the few variables it's been happening with (which are all formatted the same, if that matters) it's not always the same ones in each app. I can't figure out if it's an R issue or a shiny issue, sometimes they're showing up correctly in R and don't get messed up until I run the app, but sometimes it happens regardless of running the app. Is this some sort of bug? Is there any workaround? The best solution I've found so far is just to manually enter those labels, but that's kind of a pain. This is the code I'm using to round.

CAWtabkypct$Homeless <- percent(round(CAWtabkypct$Homeless, 3)) 
CAWtabkypct$Housed <- percent(round(CAWtabkypct$Housed, 3))

This is the output I get, and what the graphs look like in the app.

output graphs

I wouldn't even know how to begin to share a reproducible example, so please let me know if anyone knows what's going on or if there's any more information I can provide.

EDIT: here is a very minimal reproducible example:

CAWtabkyhml <- c(0.3756009, 0.2974416, 0.3269574)
CAWtabkyhsd <- c(0.1410886, 0.2504221, 0.6084893)

CAWtabkypcthml <- percent(round(CAWtabkyhml, 3))
CAWtabkypcthsd <- percent(round(CAWtabkyhsd, 3))

Upvotes: 0

Views: 345

Answers (1)

MrFlick
MrFlick

Reputation: 206197

The percent() function does it's own rounding. You should just use that feature rather than bothering with round()

CAWtabkypcthml <- scales::percent(CAWtabkyhml, accuracy=.1)
CAWtabkypcthsd <- scales::percent(CAWtabkyhsd, accuracy=.1)
CAWtabkypcthml
# [1] "37.6%" "29.7%" "32.7%"
CAWtabkypcthsd
# [1] "14.1%" "25.0%" "60.8%"

Upvotes: 1

Related Questions