mercredi 3 avril 2019

If/If else statements

Write R code that takes a square character matrix and checks if any of the character strings on the diagonal (top left to bottom right) begin with the letter g, (lowercase or uppercase). If satisfied, these specific entries should be overwritten with the string "HERE". Otherwise, the entire matrix should be replaced with an identity matrix (all the diagonal values are 1 and all other values are 0) of the same dimensions. Try your code on the following matrices, checking the results each time: mymat <- matrix(as.character(1:16),4,4) mymat <- matrix(c("DANDELION", "Hycinthus", "Gerbera", "MARIGOLD", "geranium", "ligularia", "Pachysandra", "SNAPDRAGON", "GLADIOLUS"),3,3) mymat <- matrix(c("GREAT", "exercises", "right", "here"),2,2,byrow=T)

mycode <- function(mat)
{
  variable <- 0

  for(x in c(1:nrow(mat)))
  {
    if(substr(mat[x,x],1,1)=='g'||substr(mat[x,x],1,1)=='G')
    {
      variable <- 1
      mat[x,x]="HERE"
    }
  }
  if(variable=1) {
    return(mat)
  }
   if(variable=0)
   {return(diag(1,nrow(mat)))
     }
      }

Aucun commentaire:

Enregistrer un commentaire