Including a vector element in an if statement
If all you want is a count, then you can construct a logical vector and count the TRUEs: sum(a9 < (mean(a9) / 2))
On Sun, Apr 19, 2009 at 5:58 PM, Enda Hargaden <endahargaden at gmail.com> 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.
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.)
Thanks a lot,
Enda
? ? ? ?[[alternative HTML version deleted]]
______________________________________________ R-help at 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.
Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem that you are trying to solve?