1

Using R, I want to reverse all the elements in each column, for a single row of a matrix. I can get the row order to reverse (which is not what I want), but not the elements in the rows.

create example matrix

snips <- c("CCA", "ATC", "TTC")
row2 <- 1:3
my.matrix <- as.matrix(rbind(snips, row2))
my.matrix

[,1]  [,2]  [,3] 

snips "CCA" "ATC" "TTC"
row2  "1"   "2"   "3" 

reverse the elements in the row = snips

my.matrix.reversed <- rev(my.matrix[my.matrix[1,], ])

Error in my.matrix[my.matrix[1, ], ] : subscript out of bounds

what I want to get is:

[,1]  [,2]  [,3] 
snips "ACC" "CTA" "CTT"
row2  "1"   "2"   "3" 
McGrady
  • 10,869
  • 13
  • 47
  • 69
MycoP
  • 137
  • 5

3 Answers3

1

One approach would be to use one of the string manipulation packages, like "stringi" to reverse the strings:

library(stringi)
my.matrix[1, ] <- stri_reverse(my.matrix[1, ])
my.matrix
#       [,1]  [,2]  [,3] 
# snips "ACC" "CTA" "CTT"
# row2  "1"   "2"   "3"  
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
0

We may need some string manipulation. Assuming there are only 3 characters in the original dataset, we can capture each character as a group ((.)) in sub and reverse the order of capture groups (`\3\2\1')

my.matrix[1,] <- sub("(.)(.)(.)", "\\3\\2\\1", my.matrix[1,])
my.matrix
#      [,1]  [,2]  [,3] 
#snips "ACC" "CTA" "CTT"
#row2  "1"   "2"   "3"  

A more generalized approach would be to split the string into individual characters, then rev and paste it back

my.matrix[1,] <- sapply(strsplit(my.matrix[1,], ""), function(x) paste(rev(x), collapse=""))

Or using Biostrings

library(Biostrings)
my.matrix[1,] <- reverse(my.matrix[1,])
akrun
  • 874,273
  • 37
  • 540
  • 662
0

You could use stringi::stri_reverse. This code assumes that the only other row is row2 and it contains only single characters, so reversal doesn't matter. If that isn't the case you need to apply the function to only the snips row.

library(stringi)
apply(my.matrix, 1:2, function(x) stri_reverse(x))

       [,1]  [,2]  [,3] 
snips "ACC" "CTA" "CTT"
row2  "1"   "2"   "3"  

Lots of other solutions at this question.

Community
  • 1
  • 1
neilfws
  • 32,751
  • 5
  • 50
  • 63