Conversation
|
|
||
| #### Note on zero-length RHS and `by` | ||
|
|
||
| * If the `RHS` of an assignment results in a zero-length vector (e.g., `numeric(0)`), `data.table` will usually throw an error. However, when using `by`, a zero-length result for a specific group is treated as a no-op (the column remains unchanged for that group) and no error is thrown. This is intentional to allow functions that might return no data for certain subsets to complete without crashing the entire operation. |
There was a problem hiding this comment.
-
what does usually mean here?
-
remains unchanged also might not be true? what if we add a column with a zero-length RHS.
-
what about
set?
There was a problem hiding this comment.
i will remove the usually mentioned and make the distinction explicit
-
regarding remains unchanged , you are right this only applies to existing columns, I checked the behavior for new columns as well, and groups returning a zero-length result are initialized with NA
-
for set i checked these
set(DT, j="x", value=numeric(0))
and set(DT, i=1L, j="x", value=numeric(0)) both gives error , so this special handelling apperas tobe specific to grouped := with by.
| DT[i, (colvector) := val] # same (NOW PREFERRED) shorthand syntax. The parens are enough to stop the LHS being a symbol; same as c(colvector). | ||
| DT[i, colC := mean(colB), by = colA] # update (or add) column called "colC" by reference by group. A major feature of `:=`. | ||
| DT[,`:=`(new1 = sum(colB), new2 = sum(colC))] # Functional form | ||
| DT[, let(new1 = sum(colB), new2 = sum(colC))] # New alias for functional form. |
There was a problem hiding this comment.
maybe add an example for a no-op?
DT[, x := if (.N > 2) sum(col) else integer(0), by=grp]
| # 3. Multiple columns in place | ||
| # DT[i, names(.SD) := lapply(.SD, fx), by = ..., .SDcols = ...] | ||
|
|
||
| set(x, i = NULL, j, value) |
There was a problem hiding this comment.
actually I just noticed right now that we never explain j and value
There was a problem hiding this comment.
hi can you please have a look wheather this new version is correct or something needs to be changed.
thanks
closes #3912
this pr adds documentation for special handeling of zero- length RHS values in
:=assignments when usingbyhi @ben-schwen , can you please have a look at it when you got time.
thank you