gsub in for loop not running?

Viewed 97

For some reason, this gsub line in my for loop isn't executing. Basically, what I hope to do is for a specific character at the beginning and end of an element, I would like to take it out. So in my example code, I only keep values that start with 0 or get rid it it otherwise (in the code I'm working with everything stored in the matrix is a character vector, and what I want to do is remove a repeating specific character at the beginning and end of each vector). However, nothing is changed about m2 once my script finishes running

m2 <- matrix( c(2, 0, 0, 0, 2, 0, 0, 0, 2), nrow=3, ncol=3)
rownames(m2) <- c("a", "d", "e")
colnames(m2) <- c("x", "w", "z")

for (i in 1:length(rownames(m2))){
  for (j in 1:length(colnames(m2))){
    if (substr(m2[i,j], 1, 1) == "0") {
      m2 <- m2
    } else (m2 <- gsub("^.", "", m2))
  }
}

2 Answers

In m2 to replace anything which doesn't start with 0 you can use startsWith

m2[!startsWith(as.character(m2), "0")] <- ''
m2

#   x   w   z  
#a ""  "0" "0"
#d "0" ""  "0"
#e "0" "0" "" 

We can use replace

replace(m2, m2 != 0, "")
#    x   w   z  
#a ""  "0" "0"
#d "0" ""  "0"
#e "0" "0" "" 

If we need to `replace the values that doesnt start with '0'

replace(m2, substr(m2, 1, 1) != 0, "")
#   x   w   z  
#a ""  "0" "0"
#d "0" ""  "0"
#e "0" "0" "" 
Related