0

Could someone help me with a wee task I'm stuck with.

I have a df with data (let's call it X) that is as numeric values, which I need to replace with labels. For that I have another df which act as a datamap (let's call it Y), so I actually need to grab a value from X, look it up on Y, to obtain the label that will go into X.

X:
Age Gender Region

 1     2       1

 2     2       3

 2     1       1

Y:

Question Value Label

Age        1      18 to 45
Age        2      Over 45
Gender     1      male
Gender     2      female
Region     1      England
Region     2      Scotland
Region     3      Wales

What I would be looking to obtain is

Z:

Age Gender Region

18 to 45 - female - England

over 45 - female - Wales

over 45 - male - England

Of course my data frames are much bigger, X has like 246 columns and Y has 8k rows and 29 columns. Could you guys give me a hand on how to do such a replacement?

Thanks

1 Answer 1

0

Using base-r and ifelse

df <- data.frame(Age = c(1,2,2), Gender = c(2,2,1), Region= c(1,3,1))

z$Age = ifelse(df$Age==1, "18 to 45", ifelse(df$Age==2, "Over 45", NA))

z$Gender = ifelse(df$Gender==1, "male", ifelse(df$Gender==2, "female", NA))

z$Region = ifelse(df$Region==1, "England", ifelse(df$Region==2, "Scotland", ifelse(df$Region==3, "Wales",NA)))
z <- data.frame(z)
z

# z
#     Age         Gender   Region
# 1 18 to 45      female   England
# 2  Over 45      female   Wales
# 3  Over 45      male     England
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot, but take into account that's just a tiny fragment of my data sets, so I can't manually do the mapping with ifelse, already thought about that, but I would die doing it like that, plus it would not take into account future data modifications
You might try using a lookup table then.
As i mentioned, the second table is my lookup table, it's about how to reference it the bigger issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.