[R] Error message in ifthen else

Duncan Murdoch murdoch at stats.uwo.ca
Fri Oct 3 12:29:06 CEST 2008


On 03/10/2008 12:40 AM, Jason Lee wrote:
> Hi Duncan, Mark and all,
> 
> Thanks for the suggestion. I ve tried the below suggestion.
> 
> I got this error now
> 
> Error in `[<-.data.frame`(`*tmp*`, , x, value = NULL) :
>   new columns would leave holes after existing columns
> 
> Its weird as I try to assign NULL manually and its not complaining anything.
> When I put that on a loop, it gives me the above error.

The problem is that assigning NULL to a list entry is the way you delete 
that entry.  Your filterpred is a dataframe, which is a list.  Assigning 
NULL to column 1 would delete column 1, changing the number of every 
following column.  Then eventually when you try to assign something to a 
later column it won't be allowed because you can't have gaps.

If it's really your intention to delete columns, you could avoid the 
error by starting at the highest one and working backwards, i.e. having 
your loop look like

for (x in ncol(filterpred):1) ...

Duncan Murdoch

> 
> Please advise. Thanks.
> 
> On Fri, Oct 3, 2008 at 1:57 PM, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
> 
>> On 02/10/2008 10:07 PM, Jason Lee wrote:
>>
>>> Hi,
>>>
>>> I came across the below error when I try to do ifelse condition:-
>>>
>>> Error in "[<-"(`*tmp*`, test, value = rep(yes, length =
>>> length(ans))[test])
>>> :
>>>        incompatible types
>>>
>>> What I am trying to accomplish is :-
>>>
>>> for(x in 1:ncol(filterpred)){
>>>
>>> sumno<-sum(filterpred[no,x])
>>> sumyes<-sum(filterpred[yes,x])
>>>
>>> ifelse(sumno==0 && sumyes !=0,
>>> filterpred[,x]<-NULL,filterpred[,x]<-filterpred[,x])
>>> }
>>>
>>> Anything wrong here?
>>>
>> You want to use if .. else .., not ifelse.  ifelse() is a function that
>> takes a vector of logical values, and produces a vector of answers, not a
>> way to control program flow.
>>
>> It almost never makes sense to use && in ifelse(), because && always
>> produces a scalar, not a vector.  I think what you want is to replace the
>> ifelse() call with
>>
>> if (sumno==0 && sumyes !=0) {
>>  filterpred[,x]<-NULL
>> } else {
>>  filterpred[,x]<-filterpred[,x])
>> }
>>
>> Duncan Murdoch
>>
>



More information about the R-help mailing list