[R] deleting rows provisionally

David Winsemius dwinsemius at comcast.net
Fri Apr 24 14:38:48 CEST 2009


On Apr 24, 2009, at 7:50 AM, onyourmark wrote:

>
> Hi. Thanks very much for the reply and the good suggestion. It works  
> well.
> But I don't get why the for loop is not deleting anything or making  
> any
> assignments? Or I should say, doesn't answer3[-i,] delete entries from
> answer3 when the if condition is true?

No, it doesn't. It returns a copy of answer3 without the ith row, but  
it does not touch answer3,  because as Ben said before you did no  
assignment.
>
> Also, in your first solution
> answer2[-(answer2[,1]==answer2[,2]),]
>
> can I say that you are indexing answer2 by answer2[,] and all of the
> deletion is coming in the first argument and specifically you are  
> deleting
> every entry in answer2 where the first elements of the first and  
> second
> columns are the same.
Actually you are still not deleting. But the rest of you  
characterization of the process looks correct.
>
> So for example,
> if I wanted instead to switch the elements of the first and second  
> column
> whenever they are different what would I do? confused.

The easiest approach would probably be to swap their names but if you  
want to swap the entries without touching the names then something like:

temp.ans <- answer2[,2]
answer2[ , 2] <- answer2[ , 1]
answer2[ , 2] <- temp.ans

Or possibly answer2[ , c(2,1)] <- answer2[ , c(1,2)] but I am not a  
sufficiently experienced R programmer to know the answer to that  
without testing.

-- 
David.
>
>
> Ben Bolker wrote:
>>
>> onyourmark wrote:
>>>
>>> I have an object. I think it is a matrix, called 'answer2'
>>> str(answer2)
>>> int [1:1537, 1:2] 1 399 653 2 3 600 4 5 271 870 ...
>>> - attr(*, "dimnames")=List of 2
>>>  ..$ : chr [1:1537] "a4.1" "hirschsprung.399" "peritoneal.653"
>>> "abdomen.2" ...
>>>  ..$ : chr [1:2] "row" "col"
>>>
>>>
>>> I want to delete rows that have the same entries.
>>>
>>>
>>
>> Your "for" loop didn't make any assignments.
>> How about
>>
>> answer3 <- answer2[-(answer2[,1]==answer2[,2]),]
>>
>> or
>>
>> answer3 <- answer2[answer2[,1]!=answer2[,2],]
>>
>> (which will be much faster than a loop anyway)


David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list