The problem I have is this. I have a data frame containing four columns, named CSES
. I have a separate data frame named meta
, containing two columns, code
and name
. If a value in any of the CSES
columns match meta$code
I want to replace it with the value in meta$name
.
Currently my solution uses for loops and is fine; but is there a better way to do this that avoids the loops, preferably using the Tidyverse? Seems like a pretty standard question that should have a answer already but I didn't find any. I am thankful for any help. Cheers.
for(i in seq_along(meta$code)) {
code <- meta$code[[i]]
for(k in seq_along(CSES)) {
col <- CSES[[k]]
col[col == code] <- meta$name[[i]]
CSES[[k]] <- col
}
}
EDIT: I added input data and desired output below and clarification of desired output per request.
To clarify, it is desired that if the meta$code
column matches a value in CSES
the value in CSES
should be changed to the meta$name
value on the same row as the matching meta$code
.
CSES, this is the data I want to recode:
# A tibble: 274,719 x 6
# IMD5000_A IMD5000_B IMD5000_C IMD5000_D IMD5000_E IMD5000_F
# <chr> <chr> <chr> <chr> <chr> <chr>
# 1 320001 320002 320003 320004 320005 320006
# 2 320001 320002 320003 320004 320005 320006
# 3 320001 320002 320003 320004 320005 320006
# 4 320001 320002 320003 320004 320005 320006
# 5 320001 320002 320003 320004 320005 320006
# 6 320001 320002 320003 320004 320005 320006
# 7 320001 320002 320003 320004 320005 320006
# 8 320001 320002 320003 320004 320005 320006
# 9 320001 320002 320003 320004 320005 320006
# 10 320001 320002 320003 320004 320005 320006
# … with 274,709 more rows
Meta:
# A tibble: 44 x 2
# code name
# <chr> <chr>
# 1 7520001 SAP
# 2 7520002 M
# 3 7520003 FP
# 4 7520004 KD
# 5 7520005 MP
# 6 7520006 C
# 7 7520007 V
# 8 7520008 SD
# 9 7520009 Fi
#10 7520010 Jl
# … with 34 more rows
For example the value 7520001 in CSES should be changed to "SAP".
dput
such that people can directly import the test data into their own R session :). When @IceCreamToucan came up with his answer he had to generate his own test data, it would've been better if you had supplied him some up front. That way you're more likely to get help and get it faster. – Peter H.dput()
stackoverflow.com/questions/49994249/example-of-using-dput – Filip Sjöstrand