当data.table:=是上一个操作

时间:2018-08-30 09:41:38

标签: r return data.table

将data.table df作为输入的函数使用data.table:=操作应返回修改后的data.table,但即使使用显式return(df)语句也不会返回任何内容。 如果我们使用data.table(df)强制转换为data.table,则该函数将返回data.table。

此行为背后的原因是什么?以及使用data.table:=运算符对函数进行编码的良好做法是什么?

这是一个最小的示例:

library(data.table)

data <- data.table(x = 1:3)

test_function_1 <- function(df){
    df[, new_column := 1]
}

test_function_2 <- function(df){
    df[, new_column := 1]
    return(df)
}

test_function_3 <- function(df){
    df[, new_column := 1]
    data.table(df)
}

test_function_1(data) # returns nothing
test_function_2(data) # returns nothing
test_function_3(data) # returns the modified data.table

如果需要,这是我的sessionInfo():

> sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)


Matrix products: default

    [...]

attached base packages:
[1] stats     graphics  grDevices utils     datasets 
[6] methods   base     

other attached packages:
[1] data.table_1.11.4

1 个答案:

答案 0 :(得分:2)

library(data.table)

data <- data.table(x = 1:3)

test_function_1 <- function(df){
    df[, new_column := 1][]
}

test_function_2 <- function(df){
    df[, new_column := 1][]
    return(df)
}

test_function_3 <- function(df){
    df[, new_column := 1]
    data.table(df)
}

test_function_1(data) # returns the modified data.table
test_function_2(data) # returns the modified data.table
test_function_3(data) # returns the modified data.table

更多信息:H E R E