R - 创建一个新变量,其中每个观察值取决于数据帧中的另一个表和其他变量 [英] R - Create a new variable where each observation depends on another table and other variables in the data frame

查看:90
本文介绍了R - 创建一个新变量,其中每个观察值取决于数据帧中的另一个表和其他变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个表:

df <- data.frame(eth = c("A","B","B","A","C"),ZIP1 = c(1,1,2,3,5))
Inc <- data.frame(ZIP2 = c(1,2,3,4,5,6,7),A = c(56,98,43,4,90,19,59), B = c(49,10,69,30,10,4,95),C = c(69,2,59,8,17,84,30))

eth    ZIP1         ZIP2    A    B    C
A      1            1      56   49   69
B      1            2      98   10   2
B      2            3      43   69   59
A      3            4      4    30   8
C      5            5      90   10   17
                    6      19   4    84
                    7      59   95   39

我想在df数据框中创建一个变量Inc,其中对于每个观察值,的eth和ZIP的观察。在我的例子中,它将导致:

I would like to create a variable Inc in the df data frame where for each observation, the value is the intersection of the eth and ZIP of the observation. In my example, it would lead to:

   eth    ZIP1   Inc        
    A      1    56
    B      1    49
    B      2    10
    A      3    43
    C      5    17

循环或相当暴力可以解决它,但它需要时间在我的数据集,我正在寻找一个更微妙的方式,也许使用data.table。在我看来,这是一个非常标准的问题,我是道歉,如果它是,我无法为这个问题制定一个精确的标题(你可能已经注意到..)也许为什么我没有找到任何类似的问题在论坛上搜索..

A loop or quite brute force could solve it but it takes time on my dataset, I'm looking for a more subtle way maybe using data.table. It seems to me that it is a very standard question and I'm apologizing if it is, my unability to formulate a precise title for this problem (as you may have noticed..) is maybe why I haven't found any similar question in searching on the forum..

谢谢!

推荐答案

关于这个?

library(reshape2)
merge(df, melt(Inc, id="ZIP2"), by.x = c("ZIP1", "eth"), by.y = c("ZIP2", "variable"))
  ZIP1 eth value
1    1   A    56
2    1   B    49
3    2   B    10
4    3   A    43
5    5   C    17

这篇关于R - 创建一个新变量,其中每个观察值取决于数据帧中的另一个表和其他变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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