自分で解決できないタスクを作成しました。一部のプロジェクトの開始日と終了日を含むデータフレームがあります。一部の要素が間違っており、終了日ではなくプロジェクトの期間が表示されます。
start_date <- c("2017-05-04", "2016-04-01", "2013-12-12", "2011-05-11", "2010-04-10", "2009-01-01")
end_date <- c("2020-01-01", "2020-01-06", "3 years", "36 months", "2020-01-01", "2020-01-01")
df <- data.frame(start_date, end_date)
start_date end_date
1 2017-05-04 2020-01-01
2 2016-04-01 2020-01-06
3 2013-12-12 3 years
4 2011-05-11 36 months
5 2010-04-10 2020-01-01
6 2009-01-01 2020-01-01
それらを計算して日付形式に変換する方法は?さらに、データ構造start_date
とがend_date
要因です。
as.Date
終了日に使用してlubridate::as.duration
から、失敗した値(つまり、NA)に使用できます。
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#>
#> date
start_date <- c("2017-05-04", "2016-04-01", "2013-12-12", "2011-05-11", "2010-04-10", "2009-01-01")
end_date <- c("2020-01-01", "2020-01-06", "3 years", "36 months", "2020-01-01", "2020-01-01")
df <- data.frame(start_date = as.Date(start_date), end_date, stringsAsFactors = FALSE)
df$EndDate <- as.Date(df$end_date)
for (i in which(is.na(df$EndDate))) {
df[i, ]$EndDate <- as.Date(df[i, ]$start_date + as.duration(df[i, ]$end_date))
}
df
#> start_date end_date EndDate
#> 1 2017-05-04 2020-01-01 2020-01-01
#> 2 2016-04-01 2020-01-06 2020-01-06
#> 3 2013-12-12 3 years 2016-12-11
#> 4 2011-05-11 36 months 2014-05-10
#> 5 2010-04-10 2020-01-01 2020-01-01
#> 6 2009-01-01 2020-01-01 2020-01-01
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加