Change value in one row after comparison with the next row in R -
i have dataframe follows
position chr score 10101 chr1 0 4509 chr1 3.58051 10745 chr1 0 2344 chr1 0 7165 chr1 -2.59335 6752 chr1 -2.655688 7441 chr1 0 7588 chr1 -4.022041 10671 chr1 0
if z score has non-zero value convert 0 if previous value 0 or non-zero in different direction (ie positive or negative).
for above dataset end looking follows:
position chr score 10101 chr1 0 4509 chr1 0 10745 chr1 0 2344 chr1 0 7165 chr1 -2.59335 6752 chr1 -2.655688 7441 chr1 0 7588 chr1 0 10671 chr1 0
i figure need apply function dont know how utilize it. can help?
so know going little clunky, vectorized (sort of) solution there's that. technically in 1 line, 1 heck of line!
first set different vectors compare, "test" replication of score column
test<-c(0,3,0,0,-2,-2,0,-4,0) #elements higher element i, between 2 , length(test)-1 higher<-test[3:length(test)] #elements lower element i, same definition above lower<-test[1:(length(test)-2)] #our ith elements mid<-test[2:(length(test)-1)]
then can reset mid @ 1 time via ifelse
#if i-1 != 0 , i-1 has same sign i, maintain i, else 0 newscore<-ifelse((lower!=0)&(sign(lower)==sign(mid)),mid, 0) #[1] 0 0 0 -2 -2 0 0
then set endpoints 0 set in comments, , reset score
newscore<-c(0,newscore, 0) #[1] 0 0 0 0 -2 -2 0 0 0 df$score<-newscore
here alternative ifelse provided above, keeps consecutive numbers of same sign
newscore<-ifelse((lower!=0), ifelse(((sign(lower)==sign(mid))), mid, 0), ifelse(sign(higher)==sign(mid), mid, 0))
and when running previous code next test vector
test<-c(0,3,4,5,0,0,2,2,2,0)
and alternative ifelse result is
#[1] 0 3 4 5 0 0 2 2 2 0
r
No comments:
Post a Comment