Message-ID: <51460335-851A-468E-8D7C-A11889F7543B@comcast.net>
Date: 2011-08-01T23:13:15Z
From: David Winsemius
Subject: if function problems
In-Reply-To: <1312239443964-3710995.post@n4.nabble.com>
On Aug 1, 2011, at 6:57 PM, zoe_zhang wrote:
> Dear All,
> Sorry to bother
> I want to write a function in R using if
> Say I have a dataset x,
> if x[i]<0, then x[i]=x[i],
> if x[i]>0, then x[i]=0
>
> for example, x=-3:3,
> then using the function, x becomes [-3,-2,-1,0,0,0,0]
Just use logical indexing
x[ x>0 ] <- 0
>
> I write the codes as follows,
>
> gjr=function(x)
> {lena=length(x)
> for(i in 1:lenx)
> if (x[i]<0) return (x[i])
> if (x[i]>0) return (0)
> x}
>
> but then, doing
> gjr(x?
> it only comes out with one number
'if' is not the right function. Look at
?"if"
?ifelse
(But the logical indexing is easier in this case than using ifelse.)
--
David Winsemius, MD
West Hartford, CT