簡體   English   中英

使用命名列表和 `:=` 在 R `data.table` 中設置多個列

[英]set multiple columns in R `data.table` with a named list and `:=`

使用:=創建新列是我最喜歡的 data.table 功能之一。 我知道使用它一次添加多個列的兩種方法。 這是一個簡單的例子

dt <- data.table("widths" = seq(2, 10, 2), "heights" = 8:4)
dt
   widths heights
1:      2       8
2:      4       7
3:      6       6
4:      8       5
5:     10       4

假設我想添加兩列,一列用於區域,另一列用於周長。 第一種方法是調用,例如

new_cols <- c("areas", "perimeters")

my_fun <- function(x, y){
  areas <- x * y
  perimeters <- 2*(x + y)
  return(list(areas = areas, perimeters = perimeters))
}

dt[ , (new_cols) := my_fun(widths, heights)]
dt
   widths heights areas perimeters
1:      2       8   16        20
2:      4       7   28        22
3:      6       6   36        24
4:      8       5   40        26
5:     10       4   40        28

等效地,我們可以使用:=的函數形式,如下所示:

dt[ , `:=`("areas" = widths * heights, "perimeters" = 2*(widths + heights))]

這兩種方法都需要提前輸入新列的名稱。 您可以手動輸入它們,您可以在創建列之前將它們保存在 object 中,或者您可以在:=的左側有一個 function 來生成名稱。 我不知道的是一種在一次調用中同時獲取名稱和 output 到:=的方法。

有沒有辦法做到這一點? 這是我希望做的一個例子:

dt[ , (new_cols) := NULL] # delete the previously added area and perimeter cols.
dt[ , `:=`(my_fun(widths, heights))]
dt
   widths heights areas perimeters
1:      2       8   16        20
2:      4       7   28        22
3:      6       6   36        24
4:      8       5   40        26
5:     10       4   40        28

理想情況下,有一種方法可以讓:=看到my_fun()返回名稱,然后將這些名稱用作新列的名稱。 我知道上面會產生一個錯誤,但我想知道是否有一種簡單的方法可以獲得所需的功能,因為這在有很多列或列名取決於 function 的輸入的較大問題中很有用。

編輯:我正在尋找的關鍵是通過引用分配這些列的方法,即使用:=或 set(),並且我還想將 output 的 class 維護為data.table

評論太長了。 不漂亮:

dt[, {
    a <- my_fun(widths, heights)   
    for (x in names(a))
        set(dt, j=x, value=a[[x]])
}]

或者,如果它是由您創建的,您可以將dt傳遞給 function?

我不認為你在尋找這個,但這很有效。

data.frame(dt, my_fun(dt$widths, dt$heights))

#  widths heights areas perimeters
#1      2       8    16         20
#2      4       7    28         22
#3      6       6    36         24
#4      8       5    40         26
#5     10       4    40         28

不幸的是, data.table(dt, my_fun(dt$widths, dt$heights))不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM