[R] Seeing negative numbers to zero
(Ted Harding)
Ted.Harding at manchester.ac.uk
Fri Aug 7 23:59:46 CEST 2009
On 07-Aug-09 20:29:16, DebbieMB wrote:
> Hi,
> I am also new to R and I have a related question. I am trying
> to set negative values in a single column of a dataframe to zero
> and I can't seem to do it.
>
> I have tried:
> KN1<-subset(KN,select=c(5))
># Here I am selecting the column of the dataframe KN1 and assigning it
># the
> name KN2 - this step works
> KN2<-ifelse(KN1<=0,0,KN1)
># Here I am trying to set negative numbers to zero and leave all other
> numbers the same - this doesn't work
>
> Any help would be appreciated.
>
> Thanks,
> Debbie
How about something on the lines of:
KN1 <- data.frame(c1=c(1,-2,3,-4,5),c2=c(-1,2,-3,4,-5),c3=c(-
KN1
# c1 c2 c3
# 1 1 -1 -2
# 2 -2 2 -1
# 3 3 -3 0
# 4 -4 4 1
# 5 5 -5 2
KN2 <- KN1
KN2$c2 <- (KN2$c2>0)*KN2$c2 ## ** See below
KN2
# c1 c2 c3
# 1 1 0 -2
# 2 -2 2 -1
# 3 3 0 0
# 4 -4 4 1
# 5 5 0 2
The logic of the ** line is that:
1: (KN2$c2>0) is FALSE wherever (KN2$c2 <= 0), otherwise TRUE.
2: If x is a number, then TRUE*x = x and FALSE*x = 0
3: Hence (KN2$c2>0)*KN2$c2 is 0 wherever (KN2$c2 <= 0), and
is the same as KN2$c2 wherever (KN2$c2> 0)
Does this help?
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 07-Aug-09 Time: 22:59:42
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list