【问题标题】:data.table alternative for dplyr mutate_?dplyr mutate_ 的 data.table 替代品?
【发布时间】:2017-02-01 16:58:22
【问题描述】:

我有以下使用 dplyr 的 r 代码。 由于数据量大,我们想使用data.table。

test <- function(Act, mac, type, thisYear){
    Act %>%
    mutate_(var = type) %>%
    filter(var == mac) %>%
    filter(floor_date(as.Date(submit_ts), 'year') == thisYear)
}

行为如下

| submit_ts     | col1          | col2  |
| ------------- |---------------|-------|
| '2015-01-01'  | 'x'           | 1000  |
| '2015-01-01'  | 'y'           |  200  |
| '2015-01-01'  | 'x'           |  200  |

基本功能如下

test(act, 'x', 'col1', 2015)

result is as follows 
| submit_ts     | col1          | col2  |
| ------------- |---------------|-------|
| '2015-01-01'  | 'x'           | 1000  |
| '2015-01-01'  | 'x'           |  200  |


test(act, 200, 'col2', 2015)
result is as follows 
| submit_ts     | col1          | col2  |
| ------------- |---------------|-------|
| '2015-01-01'  | 'y'           |  200  |
| '2015-01-01'  | 'x'           |  200  |

我应该如何使用 data.table 呢?

【问题讨论】:

  • 如果您以前没有见过它们,这些是有关如何制作可重现示例的一些说明:stackoverflow.com/a/28481250
  • 另外,我无法重现您的输出。我用lubridate_1.6.0

标签: r data.table dplyr


【解决方案1】:

我们可以在data.table 中使用类似的方法

library(data.table)
library(lubridate)
test1 <- function(Act, mac, type){
    setnames(setDT(Act), type, "var")[
       var==mac & year(floor_date(as.Date(submit_ts), "year"))==thisYear]
 }

test1(dat, 2, "val")
#    submit_ts var
#1: 2013-05-05   2
#2: 2013-05-12   2

注意:floor_date 不会返回 yyyy 年份。

数据

dat <- data.frame(submit_ts= c("2013-05-05", "2012-05-10", "2013-05-12"),
                 val = c(2, 1, 2), stringsAsFactors=FALSE)
thisYear <- 2013

【讨论】:

  • type 是我们在函数中传递的列名。我们使用 mac 作为类型列的过滤选项。怎么过滤??
  • @KppatelPatel thisYear 是什么?它似乎不是函数中的参数。最好展示一个可重现的小例子,让其他人检查代码
  • 就是年份,比如 '2014' 或 '2015' 或类似的 yyyy 格式
  • @KppatelPatel 请在您的帖子中编辑一个可重现的示例,该示例可以在新的 R 会话中运行以说明您的问题。
  • @KppatelPatel 我认为您的功能无法按您的预期工作,因为使用您的 4 位“thisYear”检查 floor_date 输出
猜你喜欢
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 2018-01-03
  • 2015-12-06
  • 1970-01-01
相关资源
最近更新 更多