在 R 中合并两个数据帧,利用一个作为字典可提供更多行

问题描述 投票:0回答:1

我在 R 中有两个数据框。

其中一个很大(200k 行),其中一列(“字段”)总共有 160 个可能重复的值。 然后我有另一个充当字典的数据框。该字典有两列,第一列“field”,包含 data$fields 列中 160 个可能值中的大约 130 个,第二列称为“categories”,包含 8 个可能值。 我想在原始数据框中添加一个名为“类别”的新列,该列将具有与字段值相对应的类别。

出于示例目的:

数据

Field     | Value
Germany     1
Germany     1
Germany     1
USA         1
USA         1
Japan       1
Australia   1

词典:

Field     | Category
Germany     Europe
USA         America
Japan       Asia

合并后

Field     | Value | Category
Germany     1       Europe
Germany     1       Europe
Germany     1       Europe
USA         1       America
USA         1       America
Japan       1       Asia
Australia   1       NA

这就是我正在做的事情:

# Merge the original dataframe with the dictionary dataframe based on the 'fields' column
dat <- merge(data, dictionary, by = "field")

但是,新的数据帧从 200k 行增加到 240k 行。这是为什么?

r dataframe merge
1个回答
0
投票

您可以使用

left_join
进行合并:

library(dplyr)
left_join(df1, df2, by = "Field")
© www.soinside.com 2019 - 2024. All rights reserved.