当值落在间隔中时,使用match()分配标签 [英] Using match() to assign labels when a value falls in an interval

查看:181
本文介绍了当值落在间隔中时,使用match()分配标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新我的代码,以将标签分配给数据帧中由列指定的范围之间的值。我正在使用匹配,它只为列之间的精确匹配分配标签。如何通过与范围匹配来修改此分配标签?
示例代码如下:

I am trying to update my code to assign labels to values fall between a range specified by a column in a dataframe. I am using match which assigns labels only for exact matches between columns. How do you modify this to assign a label by matching with a range? the sample code is as follows:

library(dplyr)
a<- data.frame(source=c(1,25,41,36,45, 19), name=c("stop", "halt", "go","think","talk","sit"))

d<- a$source

t<- 0.2
al<- a$source- t
ah<- a$source + t

b= data.frame(source= c(1:50,1.1:50.1))
v=c(rbind(sort(al),ah[order(al)]))
v
c<-b %>% rowwise() %>% filter(sum((source>al)*(source<ah))>0) %>% ungroup() #thank to @lamia

c$name<-a$name[match(c$source,a$source)] # problem
c$name

正如您可以看到使用匹配仅标记两个来源之间的完全匹配。

As you can see using match only labels exact matches between the two sources. Is it possible to assign the label that "1" receives to "1.1" since it falls in the same interval.

谢谢。

推荐答案

如果你想要这个正负0.2,那么 round(x,digits = 0)为您工作;

As you want this for plus-minus 0.2, then round(x, digits = 0) would do the job for you;

c$name<-a$name[match(round(c$source),round(a$source))]

还要考虑使用 cut 如评论中所述。

For also consider using cut as mentioned in the comments.

这篇关于当值落在间隔中时,使用match()分配标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆