正如标题所说,
# 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"
答案 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"