How can I remove whitespace from a column in pipe?

Viewed 91

I am trying to as.integer() the 2nd column. This doesn't work, because of the white space. Unfortunately all attempts to remove that white space failed, too. How is this done?

library(tidyverse)

url <- "https://www.destatis.de/DE/Themen/Staat/Oeffentliche-Finanzen/Schulden-Finanzvermoegen/Tabellen/03-2021-vorlaufiger-schuldenstand-laender.html"
content <- rvest::read_html(url)

content %>%
html_table(fill = TRUE) %>% 
pluck(1) %>%
`[`(4:19,1:2) %>% 
rename(Schulden = 2)
1 Answers

You could remove the white space via e.g. stringr::str_remove before converting to a numeric:

library(tidyverse)
library(rvest)

url <- "https://www.destatis.de/DE/Themen/Staat/Oeffentliche-Finanzen/Schulden-Finanzvermoegen/Tabellen/03-2021-vorlaufiger-schuldenstand-laender.html"
content <- rvest::read_html(url)

content %>%
  html_table(fill = TRUE) %>% 
  pluck(1) %>%
  `[`(4:19,1:2) %>% 
  rename(Schulden = 2) %>% 
  mutate(Schulden = as.numeric(str_remove(Schulden, "\\s")))
#> # A tibble: 16 x 2
#>    Länder                 Schulden
#>    <chr>                     <dbl>
#>  1 Baden-Württemberg         47529
#>  2 Bayern                    17361
#>  3 Brandenburg               18836
#>  4 Hessen                    45269
#>  5 Mecklenburg-Vorpommern     8492
#>  6 Niedersachsen             66540
#>  7 Nordrhein-Westfalen      184481
#>  8 Rheinland-Pfalz           31428
#>  9 Saarland                  14489
#> 10 Sachsen                    4992
#> 11 Sachsen-Anhalt            22038
#> 12 Schleswig-Holstein        30908
#> 13 Thüringen                 16056
#> 14 Berlin                    62025
#> 15 Bremen                    34280
#> 16 Hamburg                   35216
Related