2015-11-10 32 views
1

我有一個數據框。這裏是一個示例部分。有條件地在R中添加現有日期

Lines <- "Category date 
desktop  2017-12-25 
tablet  2016-05-13 
desktop  2018-06-01 
desktop  2017-08-06 
tablet  2015-12-31" 
DF <- read.table(text = Lines, header = TRUE) 
DF$date <- as.Date(DF$date) 

數據框中有1000多行。

我想要做的是:如果類別是桌面,我怎樣才能將2年添加到現有日期?如果該類別是平板電腦,我如何才能在現有日期添加1年?感謝您的幫助!

回答

2

這不使用任何套餐。輸入數據幀是DF。該代碼在第一行中將date列轉換爲"POSIXlt"類,並給出lt,將第二行中的年份組件lt增量化,並將lt轉換回第三行中的"Date"類。 (注意,如果附加的類別是通過簡單地對多個詞語添加來實現第二行可以很容易地進行修改。)

lt <- as.POSIXlt(DF$date) 
lt$year <- lt$year + 2 * (DF$Category == "desktop") + (DF$Category == "laptop") 
DF$date <- as.Date(lt) 

,並提供:

Category  date 
1 desktop 2019-12-25 
2 tablet 2016-05-13 
3 desktop 2020-06-01 
4 desktop 2019-08-06 
5 tablet 2015-12-31 
+0

謝謝。我更新了我的問題。 :) – cutebunny

+0

好的。現在在問題中重新運行可重現的數據。 –

+0

你的答案非常簡單而且有用。謝謝! – cutebunny

0

這可能是最好的通過合併完成。

library(dplyr) 
library(lubridate) 

additions = 
    data_frame(Category = c("desktop", "tablet"), 
      interval = c(2, 1)) 

data %>% 
    left_join(additions) %>% 
    mutate(date = ymd(date), 
     interval = interval %>% as.period("year"), 
     next_date = date + interval) 
+0

爲什麼不是一個ifelse - 合併肯定是不需要的。 – jeremycg

+0

@jeremycg你能給我一個ifelse解決方案嗎?謝謝! – cutebunny

+0

@jeremycg在調整日期變量時,ifelse可能會很麻煩,請參閱http://stackoverflow.com/questions/6668963/how-to-prevent-ifelse-from-turning-date-objects-into-numeric-objects。我同意這個例子的合併過於複雜,但是如果比這兩個規則多得多,它可能是一個可行的策略。 –

1

使用ifelse

library(readr) 
library(lubridate) 
library(dplyr) 

dfX = read_table("Category date 
desktop  2017-12-25 
tablet  2016-05-13 
desktop  2018-06-01 
desktop  2017-08-06 
tablet  2015-12-31", 
       col_types = list(col_character(), col_date())) 


dfX %>% 
    mutate(date_new = ifelse(Category == "desktop", date + dyears(2), 
          ifelse(Category == "tablet", date + dyears(1), date))) 
+0

你從中得到了什麼輸出?由於這種現象,我得到'date_new'的數字:http://stackoverflow.com/questions/6668963/how-to-prevent-ifelse-from-turning-date-objects-into-numeric-objects。 –

+0

@ SamFirke已經忘記了這一點。接得好。 – tchakravarty

2

如果你有大data.frames,你可以這樣做:

library(lubridate) 
library(data.table) 

addYear = function(date, nyear){year(date)=year(date)+nyear; date} 

setDT(df)[,date:=as.Date(date)][ 
      Category=='desktop', date:=addYear(date,2)][ 
      Category=='tablet', date:=addYear(date,1)] 

# Category  date 
#1: desktop 2019-12-25 
#2: tablet 2017-05-13 
#3: desktop 2020-06-01 
#4: desktop 2019-08-06 
#5: tablet 2016-12-31 
1

或者僅使用lubridate包其years()功能:

library(lubridate) 
DF$date[DF$Category == "desktop"] <- DF$date[DF$Category == "desktop"] + years(2) 
DF$date[DF$Category == "tablet"] <- DF$date[DF$Category == "tablet"] + years(1) 

> DF 
    Category  date 
1 desktop 2019-12-25 
2 tablet 2017-05-13 
3 desktop 2020-06-01 
4 desktop 2019-08-06 
5 tablet 2016-12-31