简体   繁体   中英

How to do a VLOOKUP in R?

 #Data generation
 firm <- c("firm1","firm2","firm3","firm4")
 comment2 <- c(51,5104,"",510466)
 commenta <- c(51,51,"",51)
 commentb <- c("",04,"",04)
 commentc <- c("","","",66)

 list <- data.frame(firm,comment2,commenta,commentb,commentc)

 commentcode  <- c(51,04,66,67)
 narrcmnt <- c("less business", "more business", "unemployment", "covid")

 comment <- data.frame(commentcode,narrcmnt)

If I was to want to do a VLOOKUP on this, do I use left join or is this more involved? The end result would look like this. I know that there are three lookups involved potentially but I can figure the rest out after I get the first one. narrcmnt would correspond to commenta .

End result

  firm    comment2     commmenta      commentb      commentc   narrcmnta
  firm1   51           51                                      less business
  firm2   5104         5104               04                  
list %>% 
  left_join(comment %>% 
              mutate(commentcode = as.character(commentcode)),
            by=c("commenta" = "commentcode")) %>% 
  mutate(narrcmnt = case_when(is.na(narrcmnt) ~ "",
                              TRUE ~ as.character(narrcmnt)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM