R 如何比较两种不同的日期格式?
我想比较不同的日期格式并设置一个值。我有两个数据帧: 数据帧1:测试R 如何比较两种不同的日期格式?,r,date,merge,compare,R,Date,Merge,Compare,我想比较不同的日期格式并设置一个值。我有两个数据帧: 数据帧1:测试 head(test) number date country 1 6317004100 2012-10-30 Italy 2 6317071200 2013-12-02 Germany
head(test)
number date country
1 6317004100 2012-10-30 Italy
2 6317071200 2013-12-02 Germany
3 6317064800 2013-03-06 USA
4 6317071200 2013-11-06 Germany
5 6317071200 2013-08-12 Germany
6 6317004100 2012-10-26 Croatia
数据帧2:数据帧
head(dataframe)
date group
1 2012-07 1
2 2012-08 1
3 2012-09 2
4 2012-10 2
5 2012-11 2
6 2012-12 2
7 2013-01 3
8 2013-02 3
9 2013-03 3
10 2013-04 3
11 2013-05 3
12 2013-06 3
13 2013-07 4
14 2013-08 4
15 2013-09 4
16 2013-10 4
17 2013-11 4
18 2013-12 4
我想将test$date与dataframe$date与规则进行比较:
test$date中2012-07年的所有内容都在第1组中,2012-08年的所有内容都在第1组中,依此类推……我得到以下输出:
> test
number date country group
1 6317004100 2012-10-30 Italy 2
2 6317071200 2013-12-02 Germany 4
3 6317064800 2013-03-06 USA 4
4 6317071200 2013-11-06 Germany 4
5 6317071200 2013-08-12 Germany 4
6 6317004100 2012-10-26 Croatia 2
我试过这个:
> merge(dataframe, test, by.x="date", by.y="date")
[1] date group number country
<0 rowes> (or row.names with length 0)
>合并(数据帧,测试,by.x=“日期”,by.y=“日期”)
[1] 日期组号国家/地区
(或长度为0的row.names)
但是什么也没发生。两个日期列都是系数
有什么好办法吗?非合并选项将使用
匹配
。在这里,我们将test
转换为YYYY-MM格式,并将其与dataframe$date
匹配,得到相应的组
test$group <- dataframe$group[
match(format(as.Date(test$date), "%Y-%m"), dataframe$date)]
test
# number date country group
#1 6317004100 2012-10-30 Italy 2
#2 6317071200 2013-12-02 Germany 4
#3 6317064800 2013-03-06 USA 3
#4 6317071200 2013-11-06 Germany 4
#5 6317071200 2013-08-12 Germany 4
#6 6317004100 2012-10-26 Croatia 2
使用tidyverse
:
df1%>%
mutate(mnt=format(as.Date(date), "%Y-%m"))%>%
left_join(df2%>%mutate(date=as.character(date)),by=c("mnt"="date"))
number date country mnt group
1 6317004100 2012-10-30 Italy 2012-10 2
2 6317071200 2013-12-02 Germany 2013-12 4
3 6317064800 2013-03-06 USA 2013-03 3
4 6317071200 2013-11-06 Germany 2013-11 4
5 6317071200 2013-08-12 Germany 2013-08 4
6 6317004100 2012-10-26 Croatia 2012-10 2
您确实需要使用区域设置将日期从字符串转换为日期类型或ISO 8061格式,然后比较日期对象。日期不是字符串!我同意Dragon的想法,即最好先将它们转换为日期格式。我通常使用lubridate()包来实现这一点。我完全同意你们两位的观点,只是为了转换它所需的一些预处理步骤。谢谢你们的回答!只有一个问题,什么是测试**2**$group?@菠萝我改了名字。现在应该没事了。好的,很好!谢谢
df1%>%
mutate(mnt=format(as.Date(date), "%Y-%m"))%>%
left_join(df2%>%mutate(date=as.character(date)),by=c("mnt"="date"))
number date country mnt group
1 6317004100 2012-10-30 Italy 2012-10 2
2 6317071200 2013-12-02 Germany 2013-12 4
3 6317064800 2013-03-06 USA 2013-03 3
4 6317071200 2013-11-06 Germany 2013-11 4
5 6317071200 2013-08-12 Germany 2013-08 4
6 6317004100 2012-10-26 Croatia 2012-10 2