andrewjc
andrewjc

Reputation: 117

Compare values in one column to another in R

I am a little lost here, I feel like this should be really simple. The goal is to take data given with a range in the "# - #" format and see if the "Values" fall within that range. I need to then have a new column indicating if the "Value" was in the range given. The code below was how I thought it should look, but it does not return correct T/F statements.

Group<-c("A","B","C")
Value<-c(12,2,200)
Range<-c("5-20","5-20","5-20")

Test<-as.data.frame(cbind(Group,Value,Range))

Test<-separate(Test,Range,into = c("min","max"),sep = "-",remove = T)

Test<-mutate(Test,Pass=Test$min<Test$Value|Test$Value<Test$max))

The problem seems to stem from the minimum value this code works as expected

Test<-mutate(Test,Pass=Test$Value<Test$max)

However, this code returns all FALSE values:

Test<-mutate(Test,Pass=Test$min<Test$Value)

I must be missing something. Any help on what I am doing wrong would be much appreciated.

Upvotes: 0

Views: 913

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389235

  • Check the class of the columns that you have. as.data.frame(cbind(...)) is incorrect way of creating a dataframe. cbind converts all the values to characters. Use data.frame(...) instead so that the classes are maintained.

  • separate returns character columns, use convert = TRUE to make them as numeric.

  • The condition to check if the Value is in range should have & and not |.

library(dplyr)
library(tidyr)

Test %>%
  separate(Range,into = c("min","max"),sep = "-", convert = TRUE) %>% 
  mutate(Pass = Value > min & Value < max)

#  Group Value min max  Pass
#1     A    12   5  20  TRUE
#2     B     2   5  20 FALSE
#3     C   200   5  20 FALSE

data

Group<-c("A","B","C")
Value<-c(12,2,200)
Range<-c("5-20","5-20","5-20")
Test<- data.frame(Group,Value,Range)

Upvotes: 2

Related Questions