Phillip Black
Phillip Black

Reputation: 105

Match a table in R and return value from row

I have a column of data, state_key and info about it stored in distance_key I would like to scan state_key for matches with state_m and when there's a match I would like it to return in distance_key

Like so:

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

When you use match() it'll tell me if there is one, but I need more than that.

Upvotes: 0

Views: 3989

Answers (3)

sunny
sunny

Reputation: 3891

If you want to return a data frame of all rows that match an entry in state_m and their corresponding distance_key try the following:

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

If you merely want the corresponding distance_key values in a vector, you can more succinctly return:

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

And if state_m is a single value and not a vector of values use:

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

Upvotes: 0

Harshit_Mishra
Harshit_Mishra

Reputation: 86

User the faster and more efficient package - data.table:

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

store the list of states that you are looking for in a data 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

the entire data set of State code and distances should be stored as a data 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

Upvotes: 0

Iroha
Iroha

Reputation: 34761

You could try:

mydf[ mydf$state_key %in% state_m,]

Upvotes: 1

Related Questions