Berber Berber - 1 year ago 76
R Question

Return matching names instead of binary variables in R

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:

[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)

[1] 1 1 1

[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

Answer Source

Lets say your binary vector is

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

just use,


will give you the name for selected items, and


will give you name for unselected items

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download