如何避免此函数修改我的初始对象的类

时间:2017-10-26 10:13:10

标签: r function data.table

正如标题所说,

# install.packages(c("dplyr"), dependencies = TRUE)
library(dplyr)
tbl <- tibble(id = rep(0:1, c(7, 10)),
             grp = rep(c(0,1,0,1,2), c(3,4,2,5,3)),
             LET = rep(c('A', 'B', 'A', 'B', 'A', 'B'), c(1,4, 3, 3, 4, 2)))

# install.packages(c("data.table"), dependencies = TRUE)
library(data.table) 
class(tbl)
#> [1] "tbl_df"     "tbl"        "data.frame"
dt_by_akrun  <- function(x) {foo <- x; setDT(foo)[, grp_LET := LET[1], .(id, grp)]; as_tibble(foo)}
invisible(dt_by_akrun(tbl))
class(tbl)
#> [1] "data.table" "data.frame"

1 个答案:

答案 0 :(得分:1)

我们可以将其分配给foo <-x

,而不是分配copy(x)
dt_by_akrun  <- function(x) {foo <- copy(x)
                  setDT(foo)[, grp_LET := LET[1], .(id, grp)]
                   as_tibble(foo)
               }
invisible(dt_by_akrun(tbl))
class(tbl)
#[1] "tbl_df"     "tbl"        "data.frame"