在R中,如何根据另一个数据帧中的范围对一个数据帧中的值进行分类? [英] In R, how do you classify values in one data frame based on ranges in another data frame?

查看:88
本文介绍了在R中,如何根据另一个数据帧中的范围对一个数据帧中的值进行分类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,如何相对于另一数据帧中的因子值对数据帧的一列中的值进行分类?例如,给定df1和df2,我想生成df3(或更新df1):

 > df1 
NewAge
1 5
2 25
3 18
4 9
5 43
6 15
7 17

> df2
AgeStart AgeEnd AgeType
1 0 10 A
2 10 20 B
3 20 30 A
4 30 40 B
5 40 50 A

我想要df3为:

  NewAge类型
5 A
25 A
18 B
9 A
43 A
15 B
17 B

我使用cut()生成间隔

  df2_cut<-data.frame(NewAge,
AgeRange = cut(NewAge,
breaks = AgeStart,
right = F,
include.lowest = T))
> df2_cut
NewAge AgeRange
1 5 [0,10)
2 25 [20,30)
3 18 [10,20)
4 9 [0,10 )
5 43 [40,50]
6 15 [10,20)
7 17 [10,20)

但我不知道如何根据间隔类型(即A或B)对 df2_cut 值进行分类。 / p>

解决方案

我们可以使用 findInterval 。输出将是一个数字索引,我们将使用它从 AgeType中获取相应的元素。

  df3<-transform( df1,类型= df2 $ AgeType [findInterval(NewAge,df2 $ AgeStart)])
df3
#NewAge类型
#1 5 A
#2 25 A
#3 18 B
#4 9 A
#5 43 A
#6 15 B
#7 17 B

或在 cut 中带有 labels = FALSE p>

In general, how could I classify values in one column of a data frame with respect to factor values in another data frame? For example, given df1 and df2 I would like to generate df3 (or update df1):

> df1
  NewAge
1      5
2     25
3     18
4      9
5     43
6     15
7     17

> df2
  AgeStart AgeEnd AgeType
1        0     10       A
2       10     20       B
3       20     30       A
4       30     40       B
5       40     50       A

I want df3 as:

NewAge Type
  5      A   
 25      A
 18      B
  9      A
 43      A
 15      B
 17      B

I used cut() to generate intervals

df2_cut <- data.frame(NewAge, 
                      "AgeRange" = cut(NewAge,
                                       breaks=AgeStart, 
                                       right=F, 
                                       include.lowest=T))
> df2_cut
  NewAge AgeRange
1      5   [0,10)
2     25  [20,30)
3     18  [10,20)
4      9   [0,10)
5     43  [40,50]
6     15  [10,20)
7     17  [10,20)

but I don't know how to classify df2_cut values according to the interval type (i.e. A or B).

解决方案

We can use findInterval. The output will be a numeric index which we use to get the corresponding elements from 'AgeType'.

df3 <- transform(df1, Type=df2$AgeType[findInterval(NewAge, df2$AgeStart)])
df3
#  NewAge Type
#1      5    A
#2     25    A
#3     18    B
#4      9    A
#5     43    A
#6     15    B
#7     17    B

Or with labels=FALSE in cut

这篇关于在R中,如何根据另一个数据帧中的范围对一个数据帧中的值进行分类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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