【问题标题】:Match the values row by row of two columns of a data frame逐行匹配数据框两列的值
【发布时间】:2019-04-27 02:57:05
【问题描述】:

我有一个类似这样的数据框:

| Employee | Expense_Type    | Default_Expense | Amount |   |
|----------|-----------------|-----------------|--------|---|
| John     | Airfare         | Airfare         | 1000   |   |
| David    | Hotel_Tax       | Hotel           | 50     |   |
| Nancy    | Miscellaneous   | Undefined       | 500    |   |
| Mike     | Individual_Meal | Individual_Meal | 75     |   |
| Jenny    | Airline_tax     | Airfare         | 125    |   |

我想逐行比较“Expense_Type”和“Default_Expense”列并生成一个新列来粘贴不匹配的值。例如,从上表中,我们可以看到第 2、3 和 5 行不匹配,因为 hotel_tax 与 hotel 不同,miscellaneous 与 undefined 不同,airline_tax 与 airfare 不同。

我尝试研究遇到以下解决方案时提到的不同问题: df2$Expense_Type[!(df2$Expense_Type %in% df2$Default_Expense)] 但这似乎对我不起作用。

【问题讨论】:

    标签: r matching


    【解决方案1】:

    %in% 运算符不会比较每一行。使用== 运算符来执行此操作。这会将每一行转换为可用于过滤的布尔值:-)

    df2[df2$Expense_Type == df2$Default_Expense, ]
    

    对于值:

    df$newcol <- ifelse(df2$Expense_Type == df2$Default_Expense, "Correct", "Wrong")
    

    【讨论】:

    • 不客气。如果您喜欢我的解决方案,非常感谢您接受答案:-)
    • 我这样做了,但收到一条消息:“感谢您的反馈!声望低于 15 人的投票将被记录,但不要更改公开显示的帖子得分”
    • @hk2,您可以点击旁边的绿色箭头接受。如果您尝试投票,它会给您通知:)。
    • 就像安德鲁说的 ;-)
    猜你喜欢
    • 2021-07-22
    • 2018-05-15
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    相关资源
    最近更新 更多