Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhilfi/5548d3d457f7fb81c6c7226240f16127 to your computer and use it in GitHub Desktop.
Save rhilfi/5548d3d457f7fb81c6c7226240f16127 to your computer and use it in GitHub Desktop.
remove_all_non_numbers_from_selected_columns #r
#### Remove all non-number ####
library(tidyverse)
library(readr)
numbers<-c(1,2,3,4,5,6,7,8,9,10,11)
numbers_with_some_characters<-c("1","2zwei","3","4vier","5","6 sechs","7","8 ", " 9", "1 0", " 1 1 ")
data_to_show_remove_nonnumbers<-data.frame(numbers, numbers_with_some_characters)
cleaned<-data_to_show_remove_nonnumbers %>%
mutate_at(vars(numbers, numbers_with_some_characters), funs(gsub("[^0-9.-]", "", .)))
table(cleaned$numbers_with_some_characters)
is.numeric(cleaned$numbers_with_some_characters)
# if we want to turn it directly into numeric
cleaned<-data_to_show_remove_nonnumbers %>%
mutate_at(vars(numbers, numbers_with_some_characters), funs(as.numeric((gsub("[^0-9.-]", "", .)))))
table(cleaned$numbers_with_some_characters)
is.numeric(cleaned$numbers_with_some_characters)
# there is also the nice command parse_number from the readr package,
# but it throws an error of one column is already a number
cleaned2d<-data_to_show_remove_nonnumbers %>%
mutate_at(vars(numbers, numbers_with_some_characters), parse_number)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment