views:

186

answers:

2

I was working through the Rosetta Code example of the knapsack problem in R and I came up with four solutions. What is the best way to output only one of the solutions based on the observation number give in the table?

    > values[values$value==max(values$value),]
     I II III value weight volume
2067 9  0  11 54500     25     25
2119 6  5  11 54500     25     25
2171 3 10  11 54500     25     25
2223 0 15  11 54500     25     25

My initial idea was to save this output to a new variable, then query the new variable such as:

> newvariable <- values[values$value==max(values$value),]
> newvariable2 <- newvariable[2,]
> newvariable2
     I II III value weight volume
2119 6  5  11 54500     25     25

This gives me the desired output but is there a cleaner way to do it?

+1  A: 

I still don't totally understand what the "observation number" means in this context. Here are three easy ways to get the same value without making an assignment:

values[values$value==max(values$value) & values$I == 6,]

Or using the rownames:

values[values$value==max(values$value) & rownames(values)==2119,]

Or simply using the index the way you did it:

values[values$value==max(values$value),][2,]

Edit: I see, you just want to select a specific row. Then you can use the row number like so:

values[2119,]
Shane
For lack of a better term, I was using "observation number" to refer to the first column of data automatically generated by R (ie 2067, 2119, etc.) Is there a proper name for this column?
Stedy
I think that observations is correct then. From R's standpoint, those are the row names, the other values of interest are the column names.
Shane
+1  A: 

If I understand your problem correctly, you just want to extract the row of a data frame based on his row name ?

Then, if you want to extract the observation whose row name is 2119, the simpler may be :

values["2119",]
juba
And in typical R fashion, there is a more elegant solution that requires much less effort. Thanks!
Stedy