I am using converting back and forth from data.frame to data.table using a workflow like: setDT()
+ some data.table
operation + setDF()
(see this post). Using setDF()
will correctly transform back my input into a data.frame.
However, when I use exactly the same code, but within a function, the input is not transformed back into an data.frame anymore after a setDF()
call! I suspect this is a difference between transforming locally and globally, but I don't quite understand, and especially, don't see how to get my input back into a data.frame (setDF()
outside would work obviously, but that's not the idea).
library(data.table)
data(iris)
## using setDF outside of function
setDT(iris)
iris[, Sepal.Length.Mean := mean(Sepal.Length), by = Species]
setDF(iris)
class(iris)
#> [1] "data.frame"
## using setDF within a function
fo <- function(df){
setDT(df)
df[, Sepal.Length.Mean := mean(Sepal.Length), by = Species]
setDF(df)
df
}
res <- fo(iris)
class(iris)
#> [1] "data.table" "data.frame"
Created on 2020-11-17 by the reprex package (v0.3.0)