【问题标题】:Delete rows which are without a specific time span删除没有特定时间跨度的行
【发布时间】:2017-02-27 14:21:13
【问题描述】:

我有一个包含 40 列的数据集,每列 100.000 行,我需要过滤/减少/精简:所以我想删除 2014 年 10 月 1 日和 2016 年 8 月 20 日之后的所有订单(我想保留的时间跨度表中是 1.10.2104-20.8.2016)我该怎么做(只需从表中删除不需要的旧数据)这是一个示例:

DB <- data.frame(orderID  = c(1,2,3,4,5,6,7,8,9,10),     
orderDate = c("01.07.2014 05:11","12.08.2014 12:39","09.09.2015 09:14","04.10.2014 16:15","02.11.2015 07:04", "10.11.2015 16:52","20.02.2016 08:08","12.04.2016 14:07","24.07.2016 17:04","09.09.2016 06:04"),  
itemID = c(2,3,2,5,12,4,2,3,1,5),  
size = c("m", "l", 42, "xxl", "m", 42, 39, "m", "m", 44),
color = c("green", "red", "blue", "yellow", "red", "yellow", "blue", "red", "green", "black"),
manufacturer = c("11", "12", "13", "12", "13", "13", "12", "11", "11", "13")
customerID = c(1, 2, 3, 1, 1, 3, 2, 2, 1, 1)

预期结果:

DB <- data.frame(orderID  = c(3,4,5,6,7,8,9),     
orderDate = c("09.09.2015 09:14","04.10.2014 16:15","02.11.2015 07:04", "10.11.2015 16:52","20.02.2016 08:08","12.04.2016 14:07","24.07.2016 17:04"),  
itemID = c(2,5,12,4,2,3,1),  
size = c(42, "xxl", "m", 42, 39, "m", "m"),
color = c("blue", "yellow", "red", "yellow", "blue", "red", "green"),
manufacturer = c("13", "12", "13", "13", "12", "11", "11")
customerID = c(3, 1, 1, 3, 2, 2, 1)

【问题讨论】:

  • 看看this post。您还可以使用 lubridate 和 dmy_hm 来格式化您的日期

标签: r


【解决方案1】:

定义数据的示例代码中缺少逗号和右括号。

修复后,数据定义如下(由 dput 生成):

structure(list(orderID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), orderDate = structure(c(1L, 
8L, 4L, 3L, 2L, 6L, 9L, 7L, 10L, 5L), .Label = c("01.07.2014 05:11", 
"02.11.2015 07:04", "04.10.2014 16:15", "09.09.2015 09:14", "09.09.2016 06:04", 
"10.11.2015 16:52", "12.04.2016 14:07", "12.08.2014 12:39", "20.02.2016 08:08", 
"24.07.2016 17:04"), class = "factor"), itemID = c(2, 3, 2, 5, 
12, 4, 2, 3, 1, 5), size = structure(c(5L, 4L, 2L, 6L, 5L, 2L, 
1L, 5L, 5L, 3L), .Label = c("39", "42", "44", "l", "m", "xxl"
), class = "factor"), color = structure(c(3L, 4L, 2L, 5L, 4L, 
5L, 2L, 4L, 3L, 1L), .Label = c("black", "blue", "green", "red", 
"yellow"), class = "factor"), manufacturer = structure(c(1L, 
2L, 3L, 2L, 3L, 3L, 2L, 1L, 1L, 3L), .Label = c("11", "12", "13"
), class = "factor"), customerID = c(1, 2, 3, 1, 1, 3, 2, 2, 
1, 1)), .Names = c("orderID", "orderDate", "itemID", "size", 
"color", "manufacturer", "customerID"), row.names = c(NA, -10L
), class = "data.frame")

那么一个可能的解决方案是

custom_format = "%d.%m.%Y"
date <- as.Date(substr(DB$orderDate, 1, 11), format = custom_format)
subset(DB, date > "2014-10-01" & date < "2016-08-20")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 2013-01-18
    • 1970-01-01
    相关资源
    最近更新 更多