I'm trying to create a function that compares two matrices. It will compare the element of both matrices at a certain position, and returns "greater than" "equal to" or "less than". Below is the code I have right now. However, when I tried calling the function, R does not return anything, not even an error message. I'm wondering why that is the case. Any suggestions would be helpful. Thanks.
fxn <- function(x, y) {
emptymatrix <- matrix( , nrow = dim(x)[1], ncol = dim(x)[2])
for (i in 1:dim(emptymatrix)[1]) {
for (j in 1:dim(emptymatrix)[2]) {
if (x[i, j] < y[i, j]) {
emptymatrix[i, j] <- "Less Than"
}else if (x[i, j] == y[i, j]) {
emptymatrix[i, j] <- "Equal to"
}else {
emptymatrix[i, j] <- "Greater than"
}
}
}
}
#trying to test the function
vecc1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
vecc2 <- c(4, 5, 2, 3, 1, 1, 8, 9, 10)
matrix1 <- matrix(vecc1, nrow = 3, byrow = T)
matrix2 <- matrix (vecc2, nrow=3, byrow = T)
fxn(matrix1, matrix2)
CodePudding user response:
Hi as SamR pointed out in his comment, your function doesn't return anything, because it has no return function / object in the end. He is also right about the loop thing, because R is mainly designed for tabular data and matrices it can do a lot of stuff for you under the hood. This is a great examples about some design principles R has. First we don't need to use a for loop because we can just evaluate larger equal less, on all indices (vectorized). The output will be a matrix of size M with TRUE / FALSE. we can use this matrix to index our new matrix at all TRUE position. than we just need to assign a single string "equal", "larger", or "less" that gets recycled to the length of the longer vector(/list).
vecc1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
vecc2 <- c(4, 5, 2, 3, 1, 1, 8, 9, 10)
matrix1 <- matrix(vecc1, nrow = 3, byrow = T)
matrix2 <- matrix (vecc2, nrow=3, byrow = T)
# run this to see how the comparision works
matrix1 == matrix2
foo <- function(x,y) {
m_new<-matrix(NA,nrow=dim(x),ncol=dim(x))
m_new[x==y]<-"Equal"
m_new[x<y]<-"Less Than"
m_new[x>y]<-"Greater Than"
m_new # faster
#return(m_new) is not as efficent
}
foo(matrix1,matrix2)
CodePudding user response:
You missed returning emptyMatrix
from your function.
In R, the result of the last statement in a function is returned automatically. In the original function, the last statement was the for
loop, whose value is NULL. It was returned, marked "invisible", so it didn't print.
The usual convention in R is to type the name of the object you want to return when it isn't already the last value produced. So just add one line to your function, containing emptyMatrix
.
You can also call return(emptyMatrix)
, but that's actually less efficient.
And if you like returning things invisibly like for
loops do, you can call invisible(emptyMatrix)
as the last line. Then it won't automatically print, but you can still assign it to another variable.