Skip to content
14 changes: 13 additions & 1 deletion R/data.table.R
Original file line number Diff line number Diff line change
Expand Up @@ -1403,7 +1403,19 @@ replace_dot_alias = function(e) {
}

if (!is.null(lhs)) {
# TODO?: use set() here now that it can add new columns. Then remove newnames and alloc logic above.
if (length(cols) == 1L) {
is_new_col <- cols > ncol(x)
if (is_new_col || !is.list(x[[cols]])) {
if (is.function(jval)) {
stopf("RHS of `:=` is a function. To create a new column of functions or assign to a non-list-column, it must be wrapped in a list(), e.g., `:= list(myfun)`.")
}
if (is.list(jval) && length(jval) == 1L && is.function(jval[[1L]]) && nrow(x) > 1L) {
stopf("RHS of `:=` is a length-1 list containing a function. `data.table` does not automatically recycle lists. To create a list-column, use `rep(list(myfun), .N)`.")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is incorrect.

> data.table(x=1:2, L=list(mean))
       x             L
   <int>        <list>
1:     1 <function[1]>
2:     2 <function[1]>

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hi
i updated the condition and the tests, can you please review if something is missing/wrong ,when you have time.
thank you.

}
}
}
newnames = setdiff(lhs, names(x))
# TODO?: use set() here now that it can add new columns.Then remove newnames and alloc logic above.
.Call(Cassign,x,irows,cols,newnames,jval)
return(suppPrint(x))
}
Expand Down
10 changes: 10 additions & 0 deletions inst/tests/tests.Rraw
Original file line number Diff line number Diff line change
Expand Up @@ -21157,3 +21157,13 @@ test(2317.6, DT1[DF1, on='a', .(d = x.a + i.d)]$d, 5)
test(2317.7, DT1[DF2, on='a', e := i.e]$e, 5)
test(2317.8, DT1[DF2, on='a', e2 := x.a + i.e]$e2, 6)
test(2317.9, DT1[DF2, on='a', .(e = x.a + i.e)]$e, 6)

DT = data.table(x = 1:3)

test(2318.1, DT[, y := mean], error = "RHS of `:=` is a function")
test(2318.2, DT[, y := list(mean)], error = "RHS of `:=` is a length-1 list containing a function")
f = mean
test(2318.3, DT[, y := f], error = "RHS of `:=` is a function")
test(2318.4, DT[, y := identity(mean)], error = "RHS of `:=` is a function")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RHS is not a function here

test(2318.5, data.table(x = 1)[, y := mean], error = "RHS of `:=` is a function")
test(2318.6, data.table(x = 1:2)[, y := mean], error = "RHS of `:=` is a function")
Loading