通过匹配变量将值从一个data.frame添加到另一个data.frame

时间:2016-03-27 07:23:48

标签: r dataframe

假设我有两个数据帧df1和df2如下

Df1

Id Price Profit Month
10  5     2      1
10  5     3      2
10  5     2      3
11  7     3      1
11  7     1      2
12  0     0      1
12  5     1      2

Df2

Id Name
9  Kane
10 Jack
10 Jack
11 Will
12 Matt
13 Lee
14 Han

现在,我想在名为Df1的{​​{1}}中插入新列,并根据匹配Name

Df2获取其值

所以修改后的Df1将是

Id

4 个答案:

答案 0 :(得分:6)

df1 <- data.frame(Id=c(10L,10L,10L,11L,11L,12L,12L),Price=c(5L,5L,5L,7L,7L,0L,5L),Profit=c(2L,3L,2L,3L,1L,0L,1L),Month=c(1L,2L,3L,1L,2L,1L,2L),stringsAsFactors=F);
df2 <- data.frame(Id=c(9L,10L,10L,11L,12L,13L,14L),Name=c('Kane','Jack','Jack','Will','Matt','Lee','Han'),stringsAsFactors=F);
df1$Name <- df2$Name[match(df1$Id,df2$Id)];
df1;
##   Id Price Profit Month Name
## 1 10     5      2     1 Jack
## 2 10     5      3     2 Jack
## 3 10     5      2     3 Jack
## 4 11     7      3     1 Will
## 5 11     7      1     2 Will
## 6 12     0      0     1 Matt
## 7 12     5      1     2 Matt

答案 1 :(得分:6)

left_join

中使用dplyr
library(dplyr)
left_join(df1, df2, "Id")

例如:

> left_join(df1, df2)
Joining by: "Id"
  Id Price Profit Month Name
1 10     5      2     1 Jack
2 10     5      3     2 Jack
3 10     5      2     3 Jack
4 11     7      3     1 Will
5 11     7      1     2 Will
6 12     0      0     1 Matt
7 12     5      1     2 Matt
RStudio的

Data wrangling cheatsheet是一个非常有用的资源。

答案 2 :(得分:3)

以下是使用data.table

的选项
library(data.table)
setDT(Df1)[unique(Df2), on = "Id", nomatch=0]
#   Id Price Profit Month Name
#1: 10     5      2     1 Jack
#2: 10     5      3     2 Jack
#3: 10     5      2     3 Jack
#4: 11     7      3     1 Will
#5: 11     7      1     2 Will
#6: 12     0      0     1 Matt
#7: 12     5      1     2 Matt

或者@Arun在评论中提到,我们可以在加入:=“Id”后分配(on)“名称”列,以反映原始数据集“Df1”中的更改。< / p>

setDT(Df1)[Df2, Name:= Name, on = "Id"]
Df1

答案 3 :(得分:1)

简单的基础R选项可以是merge()

merge(Df1,unique(Df2), by="Id")
#  Id Price Profit Month Name
#1 10     5      2     1 Jack
#2 10     5      3     2 Jack
#3 10     5      2     3 Jack
#4 11     7      3     1 Will
#5 11     7      1     2 Will
#6 12     0      0     1 Matt
#7 12     5      1     2 Matt

此处使用函数unique(),因为Df2中有关“Jack”的重复条目。对于OP中描述的示例数据,可以省略选项by="Id",但在更一般的情况下可能是必要的。

相关问题