Timo V
Timo V

Reputation: 141

Replace multiple values in one cell

I want to replace all the long names with codes. Some cells have 20 or more of that long names and i prefer the codes.

I have two dataframes:

Result

Number   Omschrijving  functie
102040   Kadaster      Grondwerker Landmeter
104510   Graven sleuf  Stratenmaker Grondwerker Landmeter

Functiecode

functie        code
Stratenmaker   F1
Grondwerker    F3
Landmeter      F17

Expected output:

df

Number   Omschrijving  functie
102040   Kadaster      F3 F17
104510   Graven sleuf  F1 F3 F17

Because in the column functie there more than one strings, i don't know how to fix this.

I tried subset, rbind, cbind and merge but the output is not what I need .


Data:

Result <- read.table(text = "
Number,Omschrijving,functie
102040,Kadaster,Grondwerker Landmeter
104510,Graven sleuf,Stratenmaker Grondwerker Landmeter
", header = TRUE, sep = ",")

Functiecode <- read.table(text = "
functie        code
Stratenmaker   F1
Grondwerker    F3
Landmeter      F17
", header = TRUE)

Upvotes: 1

Views: 41

Answers (1)

zx8754
zx8754

Reputation: 56249

Split on space " ", then replace with lookup:

lookup <- setNames(Functiecode$code, Functiecode$functie)

Result$functie <- lapply(strsplit(Result$functie, " "), function(i){
  paste(lookup[ i ], collapse = " ")
})

Result
#   Number Omschrijving   functie
# 1 102040     Kadaster    F3 F17
# 2 104510 Graven sleuf F1 F3 F17

Upvotes: 2

Related Questions