R 基于另一列的值创建具有负值和正值的新列
有关输入数据,请参见末尾的注释。它本来有问题,但似乎已经消失了 1)yearmon将日期转换为yearmon类。在内部,它表示日期,1月为+0,2月为+1/12,…,12月为+11/12,因此减去2015年5月的1月,然后将差值乘以12,即为月数。我们还使用R 基于另一列的值创建具有负值和正值的新列,r,R,有关输入数据,请参见末尾的注释。它本来有问题,但似乎已经消失了 1)yearmon将日期转换为yearmon类。在内部,它表示日期,1月为+0,2月为+1/12,…,12月为+11/12,因此减去2015年5月的1月,然后将差值乘以12,即为月数。我们还使用sub只取当月的前3个字母,因为这是R识别的缩写形式 library(zoo) transform(data, period = 12 * (as.yearmon(sub("^(...).*(....)$", &
sub
只取当月的前3个字母,因为这是R识别的缩写形式
library(zoo)
transform(data, period =
12 * (as.yearmon(sub("^(...).*(....)$", "\\1\\2", testDate), "%b%Y") -
as.yearmon("2015-05")))
给予:
testDate period
1 April2014 -13
2 May2014 -12
3 June2014 -11
4 July2014 -10
5 Aug2014 -9
6 Sept2014 -8
7 Oct2014 -7
8 Nov2014 -6
9 Dec2014 -5
10 Jan2015 -4
11 Feb2015 -3
12 March2015 -2
13 April2015 -1
14 May2015 0
15 June2015 1
16 July2015 2
17 Aug2015 3
18 Sept2015 4
19 Oct2015 5
20 Nov2015 6
21 Dec2015 7
2)基本R如果我们知道日期是连续的月份,那么我们只需减去行数,就不需要包:
transform(data, period = 1:nrow(data) - match("May2015", testDate))
笔记
如果您想使用tidyverse软件包,
{lubridate}
提供了一些对日期时间处理的支持
使用日期,我将月份的第一个月定义为日期。如果您需要使用年-月表示法,则可以在获得所需结果时覆盖此标记
我定义了一个日期序列,因为您没有提供可复制的示例。
希望这对你有帮助。祝你好运
library(lubridate)
# define dataframe with sequence of test-dates
data <- data.frame(testDate = seq(from = ymd("2014-04-01")
, to = lubridate::ymd("2015-12-01")
, by = "1 month"))
data %>%
# in lubridate you can define a time interval and the convert this into a period
# lubridate does not support units = "months", thus we "divide" our period into months
# with "%/%" and 1 month -> months(1)
mutate( period = interval(ymd("2015-05-01"), testDate) %>% as.period() %/% months(1)
,period2 = interval(testDate, ymd("2015-05-01")) %>% as.period() %/% months(1) )
库(lubridate)
#使用测试日期序列定义数据帧
数据%
#在lubridate中,可以定义时间间隔,并将其转换为时段
#lubridate不支持units=“months”,因此我们将周期“划分”为几个月
#使用“%/%”和1个月->个月(1)
变异(周期=间隔(ymd(“2015-05-01”),测试日期)%>%as.period()%/%months(1)
,period2=间隔(测试日期,ymd(“2015-05-01”))%>%as.period()%/%months(1))
有两件事,1)我感谢您展示您的作品,但通常最好在堆栈溢出帖子中留下一些代码,以便我们更容易复制和粘贴您的作品。看见2) 如果您试图在两个日期之间进行不相等的比较,我认为您将受益于lubridate软件包。以可复制形式显示的输入数据和您拥有的任何代码都应该在问题中。在从问题中删除之前,我已将原始数据的dput
输出放在我答案末尾的注释中。另外,请阅读标签顶部关于不使用图像的信息,因为没有人可以轻松复制您的代码和数据,而无需繁琐地重新键入。
> data
testDate
1 April2014
2 May2014
3 June2014
4 July2014
5 Aug2014
6 Sept2014
7 Oct2014
8 Nov2014
9 Dec2014
10 Jan2015
11 Feb2015
12 March2015
13 April2015
14 May2015
15 June2015
16 July2015
17 Aug2015
18 Sept2015
19 Oct2015
20 Nov2015
21 Dec2015
library(lubridate)
# define dataframe with sequence of test-dates
data <- data.frame(testDate = seq(from = ymd("2014-04-01")
, to = lubridate::ymd("2015-12-01")
, by = "1 month"))
data %>%
# in lubridate you can define a time interval and the convert this into a period
# lubridate does not support units = "months", thus we "divide" our period into months
# with "%/%" and 1 month -> months(1)
mutate( period = interval(ymd("2015-05-01"), testDate) %>% as.period() %/% months(1)
,period2 = interval(testDate, ymd("2015-05-01")) %>% as.period() %/% months(1) )