匹配 R 中的 table 和行中的 return 值

Match a table in R and return value from row

我有一列数据,state_key 和有关它的信息存储在 distance_key 我想扫描 state_key 以查找与 state_m 的匹配项,当有匹配我希望在 distance_key

中匹配 return

像这样:

   state_key distance_key state_m distance_key 
1    CA       100            NC        120
2    NC       120            OH        160
3    MA       130
4    OH       160

当你使用 match() 时它会告诉我是否有,但我需要的不止这些。

你可以试试:

mydf[ mydf$state_key %in% state_m,]

如果您想要 return 与 state_m 中的条目及其对应的 distance_key 中的条目匹配的所有行的数据框,请尝试以下操作:

df[df$state_key %in% state_m, cbind("state_key" , "distance_key")]

如果你只想在向量中得到相应的 distance_key 值,你可以更简洁地 return:

df[df$state_key %in% state_m, "distance_key"]

如果 state_m 是单个值而不是值向量,请使用:

df[df$state_key == state_m, "distance_key"]

使用更快更高效的软件包 - data.table:

install.packages("data.table")
library(data.table)

将您要查找的状态列表存储在数据中 table

list.states <- as.data.table(state_m)
setnames(list.states,1,"STATE_CODE") # give some name to your column eg: STATE_CODE
setkey(list.states,STATE_CODE) # merging would be done on STATE_CODE

州代码和距离的整个数据集应存储为数据 table

dt.state.key <- as.data.table(state_key) 
setnames(dt.state.key,1,"STATE_CODE") # same column name as in the list to be matched
setkey(dt.state.key,STATE_CODE) # merging would be done on this column

result <- merge(list.states,dt.state.key,all=F) # inner join (all=F) gives the match