首页 > 解决方案 > 使用 vlookup 值在数据框中添加新列

问题描述

我在 R 中有一个数据框。

Col1  Col2

1      21

1      20

我想要下面的输出。

Col1  Col2   Output

1     21     21

1     20     21

本质上,我想在 Col1 上为 Col2 应用查找并将结果存储在输出列中。这将确保对于第 1 列中的相同输入,将在查找中选择列中两个值中较高的值。

我已经尝试了几种方法来做到这一点,但似乎都没有奏效。

更新的数据框 -

Col1   Col2    Output

1      21       21

1      20       21

12     20       20

12     19       20

标签: rdatabasedataframevlookup

解决方案


我们可以通过 'Col1' 进行分组并更新max'Col2' 的值

library(dplyr)
df1 %>%
    group_by(Col1) %>%
    mutate(Ouput = max(Col2)) %>%
    ungroup

推荐阅读