Here is an ugly approach, which assumes that all of the blank-embedded records are in the last position. It exploits the behavior of readr::read_csv, which will produce NAs when one more entry than header columns is read-in.
suppressPackageStartupMessages({
library(dplyr)
library(glue)
library(magrittr)
library(readr)
library(stringi)
library(stringr)
library(tidyr)
})
hyphen <- "-"
numerals <- "\\s[0-9\\.]+"
chars <- "^[:graph:]\\s+"
header <- c("id", "var1", "var2", "var3", "var4", "bad")
singlemark <- "\\'"
PR7 <- c("PR7 - Autres produits d'exploitation 6.9 371 667 1 389")
n_vars <- str_extract_all(PR7, numerals)[[1]] %>%
str_squish() %>%
paste(., collapse = ",")
c_vars <- str_remove_all(PR7, numerals) %>%
str_remove_all(., hyphen) %>%
str_replace(., singlemark, "ZZ") %>%
str_squish()
# read_csv(dta.csv) -> dta
# id,var1,var2,var3,var4,bad
# PR7 Autres produits dZZexploitation,6.9,371,667,1,389
# PR7 Autres produits dZZexploitation,6.9,371,667,1389,NA
# PR7 Autres produits dZZexploitation,6.9,371,667,1,389
# PR7 Autres produits dZZexploitation,6.9,371,667,1389,NA
# PR7 Autres produits dZZexploitation,6.9,371,667,1,389
# PR7 Autres produits dZZexploitation,6.9,371,667,1389,NA
# PR7 Autres produits dZZexploitation,6.9,371,667,1,389
# PR7 Autres produits dZZexploitation,6.9,371,667,1,389
dta <- data.frame(
id =
c("PR7 Autres produits dZZexploitation",
"PR7 Autres produits dZZexploitation",
"PR7 Autres produits dZZexploitation",
"PR7 Autres produits dZZexploitation",
"PR7 Autres produits dZZexploitation",
"PR7 Autres produits dZZexploitation",
"PR7 Autres produits dZZexploitation",
"PR7 Autres produits dZZexploitation"),
var1 =
c(6.9, 6.9, 6.9, 6.9, 6.9, 6.9, 6.9, 6.9),
var2 =
c(371, 371, 371, 371, 371, 371, 371, 371),
var3 =
c(667, 667, 667, 667, 667, 667, 667, 667),
var4 =
c(1, 1389, 1, 1389, 1, 1389, 1, 1),
bad =
c(389, NA, 389, NA, 389, NA, 389, 389))
dta %<>% mutate(id = str_replace(id,"ZZ","'"))
good <- filter(dta, is.na(bad))
bad <- filter(dta, !is.na(bad))
bad %<>% mutate(var4 = paste0(var4,bad),
var4 = as.numeric(var4))
add_row(good,bad) %>% select(-bad)
#> id var1 var2 var3 var4
#> 1 PR7 Autres produits d'exploitation 6.9 371 667 1389
#> 2 PR7 Autres produits d'exploitation 6.9 371 667 1389
#> 3 PR7 Autres produits d'exploitation 6.9 371 667 1389
#> 4 PR7 Autres produits d'exploitation 6.9 371 667 1389
#> 5 PR7 Autres produits d'exploitation 6.9 371 667 1389
#> 6 PR7 Autres produits d'exploitation 6.9 371 667 1389
#> 7 PR7 Autres produits d'exploitation 6.9 371 667 1389
#> 8 PR7 Autres produits d'exploitation 6.9 371 667 1389