I'm trying to get this function to work and to run faster. It takes as input a matrix, and checks to see if x and y are both greater than 0 but less than 10. Having it run faster is also key because it currently takes long with all of these conditional statements
m
x y
B -1 -1
C 50 11
D 50 5
A 51 10
val_10 = 10
myfun(m, val_10)
and the output should looks like this
[,1] [,2]
[1,] 0 0
[2,] 10 10
[3,] 10 5
[4,] 10 10
but instead it looks like this
[,1] [,2]
[1,] 0 -1
[2,] 10 11
[3,] 10 5
[4,] 10 10
m[1,2] should be 0 and m[2,2] should be 10 in the output
myfun looks like this
myfun = function(m, val_10){
v = matrix(NA, nrow = nrow(m), ncol = 2)
for (i in 1:nrow(m) ) {
old = m[i, ]
#check if smaller than 0
if (m[i,1] < 0) {
m[i, ] = c(0, old[2])
}
#check if bigger than val_10
else if (m[i,1] > val_10 ){
m[i, ] = c(val_10, old[2] )
}
#check if smaller than 0
else if (m[i, 2] < 0){
m[i, ] = c(old[1], 0)
}
#check if bigger than val_10
else if (m[i, 2] > val_10){
m[i, ] = c(old[1], val_10 )
}
v[i,] = m[i, ]
}
return(v)
}
Aucun commentaire:
Enregistrer un commentaire