Loop for Multiple Vlookup in R -
i have data frame looks this:
lhs1=c("a","d","c","b") lhs2=c("b","a","c","i") lhs3=c("i","b","a","d") lhs4=c("a","c","b","d") df <- data.frame(lhs1,lhs2,lhs3,lhs4) lhs1 lhs2 lhs3 lhs4 1 b 2 d b c 3 c c b 4 b d d
and want add 4 more columns shows sale of each letter base on value on data frame:
category <- c("a","b","c","d","e","i") sale <- c(12,23,34,35,38,42) <- data.frame(category,sale) category sale 12 b 23 c 34 d 35 e 38 42
so data frame this:
lhs1 lhs2 lhs3 lhs4 lhs1.sale lhs2.sale lhs3.sale lhs4.sale b 12 23 42 12 d b c 35 12 23 34 c c b 34 34 12 23 b d d 23 42 35 35
kindly me create loop can create multiple vlookup r.
try this
df[paste(names(df), "sale", sep = ".")] <- look$sale[match(unlist(df), look$category)] df # lhs1 lhs2 lhs3 lhs4 lhs1.sale lhs2.sale lhs3.sale lhs4.sale # 1 b 12 23 42 12 # 2 d b c 35 12 23 34 # 3 c c b 34 34 12 23 # 4 b d d 23 42 35 35
Comments
Post a Comment