Mohammad Tanvir Ahamed
2014-Jan-09 14:25 UTC
[R] Replace value in a matrix according to a list with a list of value .
Hi there !! I have a matrix like> mm[,1] [,2] [,3] [1,] 1 11 21 [2,] 2 12 22 [3,] 3 13 23 I have a list of position index like> pos$row1 [1] 1 3 $row2 [1] 3 2 $row3 [1] 1 3 2 I have a list of values like> gty$v1 9 3 $v2 4 8 $v3 7 4 1 Now i want to replace the value of each row in mm by pos list with value gty> mm[,1] [,2] [,3] [1,] 9 11 3 [2,] 8 12 4 [3,] 7 1 4 Any suggestion regarding this problem will be very helpful . Thank you. Best regards ........................... Tanvir Ahamed Göteborg, Sweden [[alternative HTML version deleted]]
Duncan Murdoch
2014-Jan-09 14:34 UTC
[R] Replace value in a matrix according to a list with a list of value .
On 09/01/2014 9:25 AM, Mohammad Tanvir Ahamed wrote:> Hi there !! > > I have a matrix like > > mm > [,1] [,2] [,3] > [1,] 1 11 21 > [2,] 2 12 22 > [3,] 3 13 23 > > I have a list of position index like > > pos > > $row1 > [1] 1 3 > > $row2 > [1] 3 2 > > $row3 > [1] 1 3 2 > > I have a list of values like > > gty > > $v1 > > 9 3 > > > $v2 > > 4 8 > > > $v3 > > 7 4 1 > > > Now i want to replace the value of each row in mm by pos list with value gty > > > mm > [,1] [,2] [,3] > [1,] 9 11 3 > [2,] 8 12 4 > [3,] 7 1 4 > > > Any suggestion regarding this problem will be very helpful . > Thank you.Use matrix indexing. You construct a two column matrix giving the indices, and then use it as an index to assign a vector of values. In your case, the matrix should be 1 1 1 3 2 3 2 2 3 1 3 3 3 2 (which you can create as indices <- matrix(c(1,1,1,3, ... ), ncol=2, byrow = TRUE) and the vector should be 9 3 4 8 ... . Then mm[indices] <- vals will do it. Duncan Murdoch
arun
2014-Jan-09 14:40 UTC
[R] Replace value in a matrix according to a list with a list of value .
Hi, Try: res <-? do.call(rbind,lapply(seq_len(nrow(mm)),function(i) {x1 <- mm[i,]; x1[pos[[i]]] <- gty[[i]]; x1})) A.K. On Thursday, January 9, 2014 9:28 AM, Mohammad Tanvir Ahamed <mashranga at yahoo.com> wrote: Hi there !! I have a matrix like?> mm? ? ? [,1] [,2] [,3] ?[1,] ? ?1 ? 11 ? 21 ?[2,] ? ?2 ? 12 ? 22 ?[3,] ? ?3 ? 13 ? 23 I have a list of position index like?> pos$row1 [1] 1 3 $row2 [1] 3 2 $row3 [1] 1 3 2 I have a list of values like> gty$v1 ?9 ?3? $v2 ?4 ?8? $v3 ?7 ?4 ?1? ? Now i want to replace the value of each row in mm by pos list with value gty> mm? ? ? [,1] [,2] [,3] ?[1,] ? ?9 ? 11 ? 3 ?[2,] ? ?8 ? 12 ? 4 ?[3,] ? ?7 ? 1 ? 4 Any suggestion regarding this problem will be very helpful . Thank you.? Best regards ...........................? Tanvir Ahamed G?teborg, Sweden ??? [[alternative HTML version deleted]] ______________________________________________ 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.