深度复制data.frame并强制到R中的data.table

深度复制data.frame并强制到R中的data.table,r,data.table,R,Data.table,我有一个R函数,它使用data.table,但接受data.frame作为输入,我不想通过引用修改输入data.frame 为此,我首先对数据帧进行“深度复制”,例如,x2这曾经是标准强制方法(以及) x <- data.frame(a=1:5,b=1:5) fun1 <- function(x) { x2 <- data.frame(x) #'deep' copy data.table::setDT(x2) return(x2) } x2 <- fun1

我有一个R函数,它使用data.table,但接受data.frame作为输入,我不想通过引用修改输入data.frame


为此,我首先对数据帧进行“深度复制”,例如,
x2这曾经是标准强制方法(以及
x <- data.frame(a=1:5,b=1:5)

fun1 <- function(x) {
  x2 <- data.frame(x) #'deep' copy
  data.table::setDT(x2)
  return(x2)
}

x2 <- fun1(x)

class(x)
class(x2)
 x3 <- as.data.table(x)

> class(x)
[1] "data.frame"
> class(x2)
[1] "data.table" "data.frame"
> as.data.table
function (x, keep.rownames = FALSE, ...) 
{
    if (is.null(x)) 
        return(null.data.table())
    UseMethod("as.data.table")
}
<bytecode: 0x7fd9597d7d10>
<environment: namespace:data.table>
> methods(as.data.table)
 [1] as.data.table.character*  as.data.table.data.frame* as.data.table.data.table*
 [4] as.data.table.Date*       as.data.table.default*    as.data.table.factor*    
 [7] as.data.table.integer*    as.data.table.ITime*      as.data.table.list*      
[10] as.data.table.logical*    as.data.table.matrix*     as.data.table.numeric*   
[13] as.data.table.ordered*    as.data.table.table*      as.data.table.xts*       
see '?methods' for accessing help and source code
> getAnywhere(as.data.table.data.frame)
A single object matching ‘as.data.table.data.frame’ was found
It was found in the following places
  registered S3 method for as.data.table from namespace data.table
  namespace:data.table
with value

function (x, keep.rownames = FALSE, ...) 
{
    if (!identical(keep.rownames, FALSE)) {
        ans = data.table(rn = rownames(x), x, keep.rownames = FALSE)
        if (is.character(keep.rownames)) 
            setnames(ans, "rn", keep.rownames[1L])
        return(ans)
    }
    ans = copy(x)
    setattr(ans, "row.names", .set_row_names(nrow(x)))
    setattr(ans, "class", .resetclass(x, "data.frame"))
    alloc.col(ans)
}
<bytecode: 0x7fd956a0ed10>
<environment: namespace:data.table>