Home > Back-end >  Removing trailing zeros and decimal point in R
Removing trailing zeros and decimal point in R

Time:10-13

I have the following data frame:

val
4.20
4.00

I would like to remove the trailing zeros and the decimal point if there are no additional decimals. Thus, my desired end result is

val
4.2
4

I know that I can use str_remove to get rid of the trailing zeros, but I am left with the decimal point on the 4. How can I update this code to drop that decimal point?

library(tidyverse)
data.frame(val = c("4.20", "4.00")) %>% 
  mutate(val = str_remove(val, "0 $"))

Edit: The numbers must be stored as a character.

Edit 2: Figured out solution below. Since data is stored as a character, solution needs to be robust to other instances in which you might deal with regular old character strings etc. This function deals with all contingencies:

decimal_func <- function(x) {
  decimalVal_check <- function(y) {
    case_when(str_count(y, "\\.") <= 1 & str_detect(str_replace(y, "\\.", ""), "^[:digit:] $") == T ~ "Valid", TRUE ~ "Invalid")
  }
  if(decimalVal_check(x) == "Valid") {
    if(str_count(x, "\\.") == 0) {
      x
    } else {
      str_remove(x, "0 $") %>% 
        ifelse(substr(., nchar(.), nchar(.)) == ".", str_replace(., "\\.", ""), .)
    } 
  } else {
    x
  }
}

CodePudding user response:

One way:

data.frame(val = c("4.20", "4.00")) %>% 
  type.convert(as.is  =TRUE) %>% 
  as_tibble()%>%
  mutate(val = as.character(val))

# A tibble: 2 x 1
  val  
  <chr>
1 4.2  
2 4  

Using str_remove:

data.frame(val = c("4.20", "4.00")) %>%  
  mutate(val = str_remove(val, '\\.?0 $'))

  val
1 4.2
2   4

Any of the following can work:

formatC(c(1,2.40,5.06), zero.print = "")
[1] "1"    "2.4"  "5.06"
prettyNum(c(1,2.40,5.06), zero.print = "")
[1] "1"    "2.4"  "5.06"
prettyNum(c(1,2.40,5.06), drop0trailing = TRUE)
[1] "1"    "2.4"  "5.06"
formatC(c(1,2.40,5.06), drop0trailing = TRUE)
[1] "1"    "2.4"  "5.06"
  •  Tags:  
  • r
  • Related