Look up value in data frame from a single vector

1278 views r
-1

I have tried different things here but not getting my desired results. What I am trying to do is use a vector v1 <- 22201691 look up this number from a two row df. Then fill the data from df1$NC2 in another vector Output

df1

RFC        NC2
22294961   239
22200691   239
22201691   239
22701619   344
22717619   344

What I want to do is use v1 to look up and match df1$RFC and my output would be df1$NC2. So in my example my_output = 239

Here is what I tried:

#this worked sometimes but not all the time.
Output<- df1[(1:dim(df1)[1])[df1[,1]==v1],2]  

#no luck with this one  
vlookup_Output <- function(){
df1%>% 
filter(NC2 %in% c("RFC", "NC2")) %>% 
pull(v1) } 

I have also tried to use the merge functions but being that v1 is a number, trying to merge df1 didn't work either.

Like always thanks in advance for the help.

answered question

df1$NC2[df1$RFC %in% v1]

Thanks this worked, but here the problem I have. So my v1 vector is pulled from another data.frame. When I do str(v1) it is num, but when I run the script it comes out as numeric(0). Now if I manually type in the number for v1 it works perfect.

2 Answers

12

This should work:

my_output <- df1$NC2[df1$RFC %in% v1]

posted this
10

If you want a tidyverse solution, here it is.

library(dplyr)

vlookup_Output <- function(DF, x, col, out){
  DF %>% 
    filter(get(col) %in% x) %>% 
    pull(out) 
} 

v1 <- 22201691
vlookup_Output(df1, v1, "RFC", "NC2")
#[1] 239

Data.

df1 <-
structure(list(RFC = c(22294961L, 22200691L, 22201691L, 22701619L, 
22717619L), NC2 = c(239L, 239L, 239L, 344L, 344L)), class = "data.frame", row.names = c(NA, 
-5L))

posted this

Have an answer?

JD

Please login first before posting an answer.