R创建一个新列,该列的值取决于其他两个列的匹配情况

我很难把我的问题变成文字(因此标题很奇怪),但是:

I want to create a new column Earnings, that will take the value of the Price of the Date that matches the Last trading day. Like this :

   Price     Date       `Last trading day`           Earnings
  <dbl>     <date>       <date>                        <dbl>
    224. 2013-01-02   2014-02-17                      235
    224. 2013-01-02   2014-02-17                      235
    224. 2013-01-02   2014-02-17                      235
    224. 2013-01-02   2014-04-19                      260
    235. 2014-02-17   2014-04-19                      260
    260. 2014-04-19   2014-06-17                      253

我尝试了这个,但是不起作用:

   library(dplyr)
   library(plyr)
   df<-data %>%
   group_by(`Last trading day`) %>%
   mutate(Earnings = if_else(data$Date==data$`Last trading day`, Price, NA_real_))

非常感谢你的帮助。

评论
  • 囚心锁
    囚心锁 回复

    We can remove the data$ as it will take the whole column by breaking the group attribute instead of the values within each group

    library(dplyr)
    data %>%
       group_by(`Last trading day`) %>%
       mutate(Earnings = if_else(Date== `Last trading day`, Price, NA_real_))
    

    Or another option is case_when

    data %>%
       group_by(`Last trading day`) %>%
       mutate(Earnings = case_when(Date== `Last trading day` ~ Price))
    

    Also, as we are comparing elementwise, we don't need any group_by

    data %>%      
       mutate(Earnings = if_else(Date== `Last trading day`, Price, NA_real_))
    

    Or with case_when remove the group_by