【问题标题】:R function returns nothing instead of data.table object when data.table := is last operation [duplicate]当 data.table := 是最后一次操作时,R 函数不返回任何内容而不是 data.table 对象[重复]
【发布时间】:2018-08-30 09:41:37
【问题描述】:

将 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

【问题讨论】:

  • := 操作符基本上改变了原始数据表并抑制打印。检查data。您会发现新列已添加到其中。相反,我建议类似于:df[,.(x,new_column=1)]。这不会改变原始 dt 并返回一个没有任何问题的表

标签: r return data.table


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 2016-08-10
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多