-1

The data set is:

col_1,col_2,value
8521,13394,24
8521,14353,15
...
1112074,1112073,52

I want a lookup for a number in the value column given numbers for the first two columns. I know using data.frame or array can solve this problem. But the maximum value in col_1 or col_2 is so big that I cannot build a 1112074*3 data.frame. How to solve this problem?

4
  • 2
    I don't understand what you are asking for. Commented Jul 29, 2014 at 4:25
  • 2
    Could you re-phrase the question to make it a little more clear? Commented Jul 29, 2014 at 4:27
  • Make a 1112074*2 data.frame having col_1 and col_2. Value can be calculated when required. Commented Jul 29, 2014 at 4:46
  • Sorry. I rephrased the question. Commented Jul 29, 2014 at 5:04

1 Answer 1

4

If i understand you correctly, you want a lookup for a number in the value column given numbers for the first two columns

Here's one way using a simple data.frame and a loop-up function

dd<-data.frame(
   col_1 = c(8521, 8521, 1112074),
   col_2 = c(13394, 14353, 1112073),
   value = c(24,15,52)
)

getval<-function(c1,c2, data=dd) {
    data$value[data$col_1==c1 & data$col_2==c2]
}

getval(8521, 14353)
# [1] 15

Unfortunately this procedure isn't very fast. If you plan to do this often, you might consider using the data.table library which allows you to index your table for faster look-up

library(data.table)
dt<-data.table(
   col_1 = c(8521, 8521, 1112074),
   col_2 = c(13394, 14353, 1112073),
   value = c(24,15,52)
)
setkey(dt, col_1, col_2)

getval<-function(c1,c2, data=dt) {
    dt[.(c1,c2)][, value]
}
getval(8521, 14353)
# [1] 15
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.