我有一个数据框。这是一个示例部分。
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年?谢谢你的帮助!
答案 0 :(得分:2)
如果你有大数据框架,你可以这样做:
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 :(得分: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
答案 2 :(得分:1)
使用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)))
:
{{1}}
答案 3 :(得分:1)
或仅为其years()
功能使用lubridate包:
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
答案 4 :(得分: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 )