[英]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.
下面的代码是我认为它应该看起来的样子,但它没有返回正确的 T/F 语句。
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:但是,此代码返回所有 FALSE 值:
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.
对我做错了什么的任何帮助将不胜感激。
Check the class of the columns that you have.检查您拥有的列的类别。
as.data.frame(cbind(...))
is incorrect way of creating a dataframe. as.data.frame(cbind(...))
是创建数据帧的不正确方式。 cbind
converts all the values to characters. cbind
将所有值转换为字符。 Use data.frame(...)
instead so that the classes are maintained.改用
data.frame(...)
以便维护类。
separate
returns character columns, use convert = TRUE
to make them as numeric. separate
返回字符列,使用convert = TRUE
使它们成为数字。
The condition to check if the Value
is in range should have &
and not |
检查
Value
是否在范围内的条件应该有&
而不是|
. .
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.