[R] replace negative numbers by smallest positive value in matrix

Juliet Hannah juliet.hannah at gmail.com
Thu Jul 15 17:55:28 CEST 2010


Hi Group,

I have a matrix, and I would like to replace numbers less than 0 by
the smallest minimum number. Below is an
small matrix, and the loop I used. I would like to get suggestions on
the "R way" to do this.

Thanks,

Juliet

# example data set

mymat <- structure(c(-0.503183609420937, 0.179063475173256, 0.130473004669938,
-1.80825226960127, -0.794910626384209, 1.03857280868547, 0.362120146065799,
-2.01124119488992, -1.49083525457822, -0.356354715035589, -0.306686279071398,
0.0789120002882668, 1.50314029609087, -0.0177677865019544, 1.31642572649823,
1.78842032090131, -0.991393884836917, -0.868946528068323, -0.325472385456867,
0.119383948888965), .Dim = c(5L, 4L))


# replacement of negative numbers

for (mycol in 1:ncol(mymat)) {
   sort_dat <- sort(mymat[,mycol])
   min_pos_index <- min(which(sort_dat >0 ))
   min_pos_val <- sort_dat[min_pos_index]
   neg_nums <- which(mymat[,mycol]  <= 0)
   mymat[neg_nums,mycol] <- min_pos_val
}



More information about the R-help mailing list