s-news
[Top] [All Lists]

Re: replacement of character in column by values

To: El Imam Hanan Attia Rizk <hanan.elimam@umontreal.ca>
Subject: Re: replacement of character in column by values
From: Rhoderick Machekano <rhoderick.machekano@case.edu>
Date: Tue, 30 Oct 2007 17:12:39 -0400
Cc: s-news@lists.biostat.wustl.edu
In-reply-to: <64E0B1A1FF5F1B4497212A108E11118F31F558@MAPIUDEM2.sim.umontreal.ca>
References: <64E0B1A1FF5F1B4497212A108E11118F31F558@MAPIUDEM2.sim.umontreal.ca>
Hanan

The following code worked on you example, although there maybe more 
efficient codes.

x=rbind(c(0,0,0,0),c(NA, NA, NA, NA),c(NA, NA, NA, NA),c(0, 0,0,0),c
(1,1,0,1),c(NA, NA, NA, NA),c(1,1,0,1))
xx=x

for(j in 1:dim(xx)[2]){
    for(i in 2:dim(xx-1)[1]){
    xx[i,j]=ifelse(is.na(xx[i,j]) & xx[i-1]==0 & xx[i+1]==0,0,x[i,j])
    xx[i,j]=ifelse(is.na(xx[i,j]) & xx[i-1]==1 & xx[i+1]==1,1,x[i,j])
    }
}

Here are the results: x is your original, and xx is the new data
> xx
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]   NA   NA   NA   NA
[3,]   NA   NA   NA   NA
[4,]    0    0    0    0
[5,]    1    1    0    1
[6,]    1    1    1    1
[7,]    1    1    0    1
> x
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]   NA   NA   NA   NA
[3,]   NA   NA   NA   NA
[4,]    0    0    0    0
[5,]    1    1    0    1
[6,]   NA   NA   NA   NA
[7,]    1    1    0    1


Rhoderick N. Machekano, Ph.D, M.P.H
Assistant Professor of Medicine
Center for Health Care Research and Policy 
Case Western Reserve University 
Email: rhoderick.machekano@case.edu 
Voice: 216 778 1952


----- Original Message -----
From: El Imam Hanan Attia Rizk <hanan.elimam@umontreal.ca>
Date: Tuesday, October 30, 2007 4:46 pm
Subject: [S] replacement of character in column by values
To: s-news@lists.biostat.wustl.edu

> Dear S Plus user
> I am working in a big data, I have two data frames that  I did 
> bind by rows (rbind)  and I gut these columns(A,B,C,D)
> 
> A    B    C    D
> 
> 0     0    0     0
> NA NA NA NA
> NA NA NA NA
> 0      0    0      0
> 1      1    0      1
> NA NA NA NA
> 1      1    0     1
> 
> I would like to go through each column and replace NA by 0 if it 
> is between 2 zeros, and if it is between two ones replace it by 1
> 
> I would really appreciate if any of you have the chance to give me 
> some suggestions.
> 
> Hanan Elimam
> Ph.D student, Pharmaceutical Sciences
> Université de Montréal
> Faculté de pharmacie
> Pavillon Jean-Coutu, bureau 3173
> 2940 Chemin de la polytechnique
> Montréal, H3T 1J4
> 
> tél.:  514-343-6111, poste 0388
> FAX: 514-343-7073
> -------------------------------------------------------------------
> -
> This message was distributed by s-news@lists.biostat.wustl.edu.  To
> unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu 
with
> the BODY of the message:  unsubscribe s-news
>

<Prev in Thread] Current Thread [Next in Thread>