Remove decimal from column in R

To remove decimals from a single column or the entire data frame, we can use str_remove from the tidyverse.

Basic syntax of str_remove:

str_remove(string, pattern)
#example:
str_remove(var, '\\.')

Since we want to remove the decimal in every row in the entire column, we can put the column name (var) in the string position and the expression with the period in the pattern position. In regular expressions (regex), the period by itself “.” indicates “any character,” so we’ll need to add the double backslash in front to specify that we want to remove the decimal. For more information on regular expressions, check out this article on the stringr package straight from the source — the Tidyverse creators.

Example

Here are 3 examples using some sample data to show how to use str_remove on 1 column, 2+ columns, and the entire data frame. 

#remove decimal from a column or entire data frame 

#load packages
library(tidyverse)

#create example data
ex_data <- tibble(id = c('1.w', '2.j', '3.e', '4.o'),
                  license_num = c('65.j8', '76.s3', '09.i0', '29.l2'))

#using str_remove on 1 column
ex1 <- ex_data %>% mutate(license_num = str_remove(license_num, '\\.'))

#using str_remove on 2+ columns
ex2 <- ex_data %>% mutate(across(1:2, ~ str_remove(., '\\.')))

#using str_remove on entire data frame
ex3 <- ex_data %>% mutate(across(everything(), ~ str_remove(., '\\.')))
Check out the related posts below for more tips!

Leave a Comment

Your email address will not be published. Required fields are marked *