簡體   English   中英

在 R 中使用向量方法根據從其他列派生的周期為列分配值

[英]Assigning value to a column based on periods derived from other columns using vector approach in R

我有一個這樣的df:

x <- data.frame("date1" = c("2018-09-12","2018-09-18", "2019-06-23"), "date2" = c("2018-09-10","2018-09-13","2018-12-12"))
> x
       date1      date2
1 2018-09-12 2018-09-10
2 2018-09-18 2018-09-13
3 2019-06-23 2018-12-12

現在我會在 date1 上做一個unique的,這將導致唯一的日期值。 然后,我將創建一個新列並根據 col date2 中的日期為其分配周期值,如下所示

     date1      date2     period
1 2018-09-12 2018-09-10   0
2 2018-09-18 2018-09-13   1 (as period 1: is 2018-09-12 to 2018-09-18 and date2 lies in it)
3 2019-06-23 2018-12-12   2  (as period 2: is 2018-09-18 to 2019-06-23 and date2 lies in that)

有沒有辦法在 R 中以矢量形式進行操作。 謝謝

你能試試這個嗎?

periods = as.Date(sort(unique(x$date1)))
x$period = apply(as.data.frame(x$date2), 1, function(x){
                findInterval(as.Date(x), periods)
            })

您可以使用date1中的日期來查找date2中的間隔

findInterval(x$date2, x$date1)
#[1] 0 1 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM