Fuv8
Fuv8

Reputation: 905

Function to compare number doesn't work as expected

I have a data.frame that looks like this:

   Col1    Col2    Col3   ......     
    30      50      90         
    50      50      20         

I would like simply to compare row 1 and row 2 of each column in this way:

if

DF[[i]][i] > DF[[i]][i + 1] --> 1 (so compare row1 with row2 of each column)

if

DF[[i]][i] < DF[[i]][i + 1] --> -1

if

DF[[i]][i] == DF[[i]][i + 1] --> 0

I tried to write the following function. Unfortunately it does not work.

 myfunc <- function(Data){   

Data = df_a_freq
if(!is.numeric(Data)){
stop("argument x must be numeric")}
value <- list()
for (i in 1: length(Data)){
if (Data[[i]][i] > Data[[i]][i+1]){
value <- 1}
else if(Data[[i]][i] < Data[[i]][i+1]){
value <- -1}
else { value <- 0
}
}
return(value)
}

When I run the function the following error occurs:

  Error in if (Data [[i]] [i]> Data [[i]] [i + 1]) {:

   missing value is required where TRUE / FALSE

I don't know how to solve it.

Upvotes: 0

Views: 83

Answers (1)

agstudy
agstudy

Reputation: 121608

Using ifelse for example:

ifelse(DF[1,] > DF[2,],1,
       ifelse(DF[1,] < DF[2,],-1,0))

Using your data :

DF <- read.table(text= 'Col1    Col2    Col3  
                 30      50      90         
                 50      50      20 ',header=TRUE    )
ifelse(DF[1,] > DF[2,],1,
       ifelse(DF[1,] < DF[2,],-1,0))

 Col1 Col2 Col3
  -1    0    1

Upvotes: 1

Related Questions