Matrix of Expression

Asked

Viewed 48 times

3

I have the following matrix on R:

 FC12h         FC10d        FC6w

-8.44770875  -0.37171750    0
-56.72384575  2.64778150    2.94636550
-3.00214850   2.64778150   -1.57755700

I need some function that causes numbers greater than zero to be equal to 1, less than zero to be equal to -1, and when 0 is equal to 0:

  FC12h         FC10d        FC6w

   -1          -1             0
   -1           1             1
   -1           1            -1

Does anyone know how I can do it?

2 answers

5


The easiest way is with the function sign. Simpler can’t be:

sign(dados)
#  FC12h FC10d FC6w
#1    -1    -1    0
#2    -1     1    1
#3    -1     1   -1

Dice.

dados <- read.table(text = "
FC12h         FC10d        FC6w
-8.44770875  -0.37171750    0
-56.72384575  2.64778150    2.94636550
-3.00214850   2.64778150   -1.57755700
", header = TRUE)

3

Being dados its headquarters,

ifelse(dados < 0, -1, ifelse(dados > 0, 1, 0) )

will return what you expect.

The function ifelse is testing if the values of dados are negative (dados < 0). If true, the value -1, otherwise, another test is performed. We now test whether the values of dados are positive (dados > 0). If true, we assign the value 1, otherwise it will be equal to 0.

The indented code, using if and else stays:

for(i in 1:nrow(dados)){
  for(j in 1:ncol(dados)){
    if(dados[i,j] < 0){
      dados[i,j] <- -1
    } else{
      if(dados[i,j] > 0){
        dados[i,j] <- 1
      } else{
        dados[i,j] <- 0
      }
    }
  }
} 
  • Hi, I don’t understand very well. What would be your indented code?

  • Vlw, man. Thank you so much. It worked!!!!

  • Consider accept the answer that helped you solve the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.