[R] replace negative numbers by smallest positive value in matrix
Phil Spector
spector at stat.berkeley.edu
Thu Jul 15 18:16:09 CEST 2010
Juliet -
Since you're operating on each column, apply() would
be the appropriate function;
mymat = apply(mymat,2,function(x){x[x<0] = min(x[x>0]);x})
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu
On Thu, 15 Jul 2010, Juliet Hannah wrote:
> 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
> }
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list