Matrix of Expression

3

I have the following array in the 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 have a value of 1, less than zero value equal to -1, and when 0 equals 0:

  FC12h         FC10d        FC6w

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

Does anyone know how I can do this?

    
asked by anonymous 09.10.2018 / 18:50

2 answers

5

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

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

Data.

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)
    
09.10.2018 / 19:47
3

Being dados its array,

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

will return what you expect.

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

Indented code, using if and else is:

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
      }
    }
  }
} 
    
09.10.2018 / 18:59