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

时间:2018-11-03 19:33:00

标签: r merge match vlookup lookup

我在这里尝试了不同的方法,但没有得到想要的结果。我正在尝试使用向量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也不起作用。

像总是感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

这应该有效:

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

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

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

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

答案 1 :(得分:0)

如果您想使用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))