从单个向量查找数据框中的值

Look up value in data frame from a single vector

我在这里尝试了不同的方法,但没有得到我想要的结果。我想做的是使用向量 v1 <- 22201691 从两行 df 中查找这个数字。然后将来自 df1$NC2 的数据填充到另一个向量 Output

df1

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

我想做的是使用 v1 查找和匹配 df1$RFC,我的输出将是 df1$NC2。所以在我的例子中 my_output = 239

这是我尝试过的:

#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) } 

我也尝试过使用合并函数,但是 v1 是一个数字,尝试合并 df1 也没有用。

一如既往地提前感谢您的帮助。

这应该有效:

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

如果该值来自另一个数据帧,则:

df2 <- data.frame(V1 = c(22201691))

df1$NC2[df1$RFC %in% df2$V1]

如果您想要 tidyverse 解决方案,就在这里。

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

数据.

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))