A Classic Model of For-Loop with Jump-out If/Else in R

0225201708
Write a conditional function 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 of the same dimensions. Then, try your code on the following matrices, checking the result each time.
</div>
mymat <- matrix(as.character(1:16),4,4)
mymat <- matrix(c("GREAT","exercises","right","gere"),2,2,byrow=T)
mymat <- matrix(c("DANDELION","Hyacinthus","Gerbera","MARIGOLD","geranium","ligularia","Pachysandra","SNAPDRAGON","GLADIOLUS"),3,3)

condfunc <- function(x){
as.data.frame(x)
for(i in 1:nrow(x)){
if((substr(x[i,i], 1, 1) == "g")|(substr(x[i,i], 1, 1) == "G")) {
x[i,i] <- "HERE"
}
}
if(x[i,i] == "HERE"){
print(x)
}
else{
x <- diag(nrow(x))
print(x)
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s