我想比较不同的日期格式并设置一个值。我有两个数据框:
数据框1:测试
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 与规则进行比较: 2012-07 中的 test$date 的所有内容都属于第 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)
但是什么也没发生。两个日期列都是因素。
有什么可行的想法吗?
最佳答案
非合并选项将使用match
。这里我们将 test
转换为 YYYY-MM 格式,并与 dataframe$date
进行匹配
,得到对应的group
。
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
合并
选项将通过创建新的Date2
列
test$Date2 <- format(as.Date(test$date),"%Y-%m")
merge(dataframe, test, by.x = "date", by.y = "Date2")
# date group number date country
#1 2012-10 2 6317004100 2012-10-30 Italy
#2 2012-10 2 6317004100 2012-10-26 Croatia
#3 2013-03 3 6317064800 2013-03-06 USA
#4 2013-08 4 6317071200 2013-08-12 Germany
#5 2013-11 4 6317071200 2013-11-06 Germany
#6 2013-12 4 6317071200 2013-12-02 Germany
关于r - 如何比较两种不同的日期格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52641961/