我很难把我的问题变成文字(因此标题很奇怪),但是:
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 groupOr another option is
case_when
Also, as we are comparing elementwise, we don't need any
group_by
Or with
case_when
remove thegroup_by