[R] Question about assigning values in a matrix, conditional on column first row; how to do the loop.

jthetzel jthetzel at gmail.com
Wed Oct 6 05:59:14 CEST 2010


Paula,

Just for fun, another way:

## Create 10 by 10 example matrix
set.seed(100)
a <- matrix(sample(c(0,1,2),100, replace=T), nrow=10, ncol=10)
a[1,] <- sample(c(0.25,0.5,0.75),ncol(a), replace=T)

## Use apply to substitiute matrix values by row
b <- apply(a, 1, function(x)
{
  row <- x
  row[row==0 | row==1] <- -999
  row[which(row==2)] <- a[1,which(x==2)]
  return(row)
})

## Transpose result matrix
b <- t(b)



Cheers,
Jeremy

Jeremy Hetzel
Boston University
-- 
View this message in context: http://r.789695.n4.nabble.com/Question-about-assigning-values-in-a-matrix-conditional-on-column-first-row-how-to-do-the-loop-tp2956355p2964227.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list