demsav demsav - 5 months ago 24
R Question

Trying to apply a classification in one dataframe, to a variable in another dataframe

despite the complicated title, what i want to do is simple:

If I have two dataframes:

d <- data.frame(V1 = c("a","b","c","d"), V2 = c("P", "M", "M", "P"))
j <- data.frame(V3 = c("d","b","b","c","d","c", "a"))

and I want to insert another column into dataframe j, called V4 which assigns the same classification in d i.e. the final dataframe will look like:


V3 V4
d P
b M
b M
c M
d P
c M
a P


You can use match

j$V4 <- d$V2[match(j$V3, d$V1)]

#   V3 V4
#1  d  P
#2  b  M
#3  b  M
#4  c  M
#5  d  P
#6  c  M
#7  a  P