从两个表中设置R中数据范围之间的标志
我有两个数据集表A和表B。两个表键都是Item 我正在编写一个R脚本,如果表A中的标志列在表B中的日期范围内,它会将其设置为“x” 我尝试使用dplyr中的between函数,在原始数据集上得到一条错误消息“期望一个值”从两个表中设置R中数据范围之间的标志,r,R,我有两个数据集表A和表B。两个表键都是Item 我正在编写一个R脚本,如果表A中的标志列在表B中的日期范围内,它会将其设置为“x” 我尝试使用dplyr中的between函数,在原始数据集上得到一条错误消息“期望一个值” Table A Item Date Flag Test1 1/1/2018 Test1 1/2/2018 x Test1 1/3/2018 x Test1 1/4/2018 x Test1 1/5/2018
Table A
Item Date Flag
Test1 1/1/2018
Test1 1/2/2018 x
Test1 1/3/2018 x
Test1 1/4/2018 x
Test1 1/5/2018
Test2 1/6/2018
Test2 1/7/2018 x
Test2 1/8/2018
Table B
Item Sdate Edate
Test 1 1/2/2018 1/4/2018
Test 2 1/7/2018 1/7/2018
您可以使用
数据中提供的非等联接执行此操作。表包:
library(data.table)
table_a <- as.data.table(table_a)
table_b <- as.data.table(table_b)
# Need to convert dates to Date class if not type Date already:
table_a[, Date := as.Date(Date)]
table_b[, Sdate := as.Date(Sdate)]
table_b[, Edate := as.Date(Edate)]
# Make sure the values in the Item column can be joined ("Test 1" should be "Test1")
table_b[, Item := gsub(" ", "", Item)]
# Create a new empty flag column
table_a[, Flag := ""]
# Non-equi join, match rows where the value in the Item column is the same and the
# value in the Date column is between the Sdate and Edate,
# then update the flag column for those rows in table_a
table_a[table_b, on = .(Item, Date >= Sdate, Date <= Edate), Flag := "x"]
库(data.table)
表a您可以使用dplyr
轻松完成此操作
library(dplyr)
TableA %>% left_join(TableB) %>% #merge in the TableB information
mutate(Flag=c("","x")[1+(as.Date(Date) >= as.Date(Sdate) &
as.Date(Date) <= as.Date(Edate))]) %>%
select(Item,Date,Flag) #remove the TableB columns
Item Date Flag
1 Test1 1/1/2018
2 Test1 1/2/2018 x
3 Test1 1/3/2018 x
4 Test1 1/4/2018 x
5 Test1 1/5/2018
6 Test2 1/6/2018
7 Test2 1/7/2018 x
8 Test2 1/8/2018
库(dplyr)
TableA%%>%左_加入(TableB)%%>%#合并到TableB信息中
变异(Flag=c(“,”x”)[1+(截止日期(Date)>=as.Date(Sdate)和
截止日期(日期)%
选择(项目、日期、标志)#删除表格B列
项目日期标志
1测试1 2018年1月1日
2测试1 2018年1月2日x
3测试1 2018年1月3日x
4测试1 2018年1月4日x
5测试1 2018年1月5日
6测试2 2018年1月6日
7测试2 2018年7月1日x
8测试2 2018年8月1日