当data.table:=是最后一个操作时,R函数返回而不返回data.table对象[duplicate]

问题描述 投票:0回答:1

这个问题在这里已有答案:

将data.table df作为输入的函数使用data.table:= operation应返回修改后的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
r return data.table
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.