0

I'm new here and diving into R, and I'm encountering a problem while trying to solve a knapsack problem.

For optimization purposes I wrote a dynamic program in R, however, now that I am at the point of returning the items, which I succeeded in, I only get the binary numbers saying whether the item has been selected or not (1 = yes). Like this:

Select [1] 1 0 0 1

However, now I would like the Select function to return the names of values instead of these binary values. Underneath I created an example of what my problem looks like.

This would be the data and a related data frame.

items <- c("Glasses","gloves","shoes")
grams <- c(4,2,3)
value <- c(100,20,50)


data <- data.frame(items,grams,value)

Now, I created various functions, with the final one clarifying whether a product has been selected by 1 (yes) or 0 (no). Like above. However, I would really like for it to return the related name of the item. Is there a manner to go around this by linking back to the dataframe created? So that it would say instead of (in case all products are selected)

Select [1] 1 1 1

Select [1] Glasses gloves shoes

I believe I would have to create a new function. But as I mentioned, is there a good way to refer back to the data frame to take related values from another column in the data frame in case of a 1 (yes)?

I really hope my question is more clear now and someone can direct me in the right direction.

Best, Berber

Berber
  • 3
  • 3
  • 3
    Sounds like a factor is being coerced or maybe you are confused about the difference between "(" and "[". Mindreading equipment not functioning at the moment, though. Cannot tell what is happening without complete code. – IRTFM Oct 25 '16 at 20:49
  • Welcome to SO. Please read [this](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Then rewrite your question to conform to these guidelines. – jlhoward Oct 26 '16 at 02:32
  • Thank you for your help so far! I'll do that. – Berber Oct 26 '16 at 08:02

1 Answers1

0

Lets say your binary vector is

idx <- [1, 0, 1, 0, 1]

just use,

items[as.logical(idx)]

will give you the name for selected items, and

items[!as.logical(idx)]

will give you name for unselected items

TheRimalaya
  • 4,232
  • 2
  • 31
  • 37