On Apr 19, 2009, at 5:58 PM, Enda Hargaden wrote:

Hi all,

I've searched high and low on this and found nothing of help. I'm using v2.6.2 and trying to write a function that will count how many people from a
dataset fall under a poverty line of 50% of the mean income.

a9 is my 100-element vector of incomes. I want pa9 to be my vector that
counts how many of these are classed as in poverty.

My problem is that my command if(a9[i] < mean(a9)/2 ) returns an "argument
is of length zero" error. But a9[i] is not really of length zero; if I
remove the if() command and simply set pa9[i] = a9[i] in the loop it comes
out fine.

I don't think it's a problem with the type of variable either, because if I
multiply the vector by 2 I get the "correct" output, so I think it's a
problem with R interpreting my vector as a list of strings or anything.

See below. the 'if' control construct is not set up to accept vectors.
From the help page ?"if"
if(cond) expr
Arguments
cond    A length-one logical vector that is not NA.


povertyline = function()
{
pa9 = c()
i=0
while(i<=length(a9))
{
   if(a9[i] < mean(a9)/2)
   {
   pa9[i] = a9[i]
   }
i = i+1
}
return(length(pa9))
}

Has anyone any ideas what's going wrong? (Just for clarification: yes, this is for my homework. However I've already done the assignment in Excel and
I'm repeating it to improve my R'ing.)

Jim gave you a perfectly workable solution, but you might find it instructive to review the difference between "if" and the function "ifelse". Generally "if" will not be useful in situations where you are doing comparisons on indexed objects whereas that is precisely what "ifelse" is designed to do. (Tthis was also pointed out in a response to a question earlier today.)


David Winsemius, MD
Heritage Laboratories
West Hartford, CT

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to