Ana
Ana

Reputation: 21

Issue with identifying negative values in r

I have a column that has positive and negative values. I’m trying to identify certain rows that meet 2 different conditions. The first condition is identifying number over a certain value. The line of code I have for this works. However, I am having trouble identifying the rows that are less than a certain (negative) number. They are not being identified at all and I’m not sure why

 taskvariables2$PC_LambdaAmbig[taskvariables2$PC_LambdaAmbig>upperbound[5,1]] <- "OB" 
 taskvariables2$PC_LambdaAmbig[taskvariables2$PC_LambdaAmbig<lowerbound[5,1]] <- "OB"

Upvotes: 0

Views: 288

Answers (2)

Ana
Ana

Reputation: 21

I just did it together instead of upper and lower bounds separately and it worked

taskvariables2$PC_LambdaAmbig[taskvariables2$LambdaAmbig > upperbound[5,1] | taskvariables2$LambdaAmbig < lowerbound[5,1]] <- "OB"

Upvotes: 0

akrun
akrun

Reputation: 887088

When we do the first assignment on the same numeric column to a character value, the column type changes to character which changes the dynamic of how the comparison operator works. Instead, use ifelse

taskvariables2$new_variable <-  with(taskvariables2, ifelse(PC_LambdaAmbig > upperbound[5,1]|
                            PC_LambdaAmbig < lowerbound[5,1], 
            "OB", PC_LambdaAmbig))

NOTE: Here, we are creating a new column instead of assigning to same old column (in case there are more comparisons to be made on the old column)

Upvotes: 1

Related Questions