Don't want original data.table to be modified when passed to a function

后端 未结 3 2012
我寻月下人不归
我寻月下人不归 2021-01-18 20:49

I am a fan of data.table, as of writing re-usable functions for all current and future needs.

Here\'s a challenge I run into while working on the answer

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-18 21:40

    Thanks to comments/answers above: this would be the easiest solution to this particular function (i.e. no need to introduce any additional .dt variable at all);

    plotYofX <- function(dt,x,y) {
      dt[,  lapply(.SD, function(x) {as.numeric(x)}), .SDcols = c(x,y)]
      ggplot(dt) + geom_step(aes(x=get(names(dt)[x]), y=get(names(dt)[y]))) + labs(x=names(dt)[x], y=names(dt)[y]) 
    

    }

    However, it was also important to learn that when working with data.table, one should be particularly careful in not making any "copies" of it with regular <- sign, but use copy(dt) instead - so that not corrupt the original data.table!
    This is further discussed in detail here: Understanding exactly when a data.table is a reference to (vs a copy of) another data.table

提交回复
热议问题