Created
July 7, 2020 05:15
-
-
Save rhilfi/5548d3d457f7fb81c6c7226240f16127 to your computer and use it in GitHub Desktop.
remove_all_non_numbers_from_selected_columns #r
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#### 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