Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent behaviour of assign := operator when grouping or not #4953

Open
pietrodito opened this issue Apr 14, 2021 · 2 comments
Open

Inconsistent behaviour of assign := operator when grouping or not #4953

pietrodito opened this issue Apr 14, 2021 · 2 comments

Comments

@pietrodito
Copy link

`# Minimal example

library(data.table)

DT <- data.table(col = c('a', 'a_b', 'a_b_c'))

DT[, c('col1', 'col2') := tstrsplit(col, '_')]
## Produces error: 
## Error in `[.data.table`(DT, , `:=`(c("col1", "col2"), tstrsplit(col, "_"))) : 
## Supplied 2 columns to be assigned 3 items. Please see NEWS for v1.12.2.

DT <- data.table(col = c('a', 'a_b', 'a_b_c'))

DT[, c('col1', 'col2') := tstrsplit(col, '_'), by = .(col)]
DT
## works:
##      col col1 col2
## 1:     a    a    a
## 2:   a_b    a    b
## 3: a_b_c    a    b

I am surprised that the second code does not produce an error.


The same confusion happens when one does that:

DT1 <- data.table(col1 = c('a', 'a_b'))
DT2 <- copy(DT1)

DT1[, c('col_a', 'col_b') := tstrsplit(col1, '_')]
DT2[, c('col_a', 'col_b') := tstrsplit(col1, '_'), by = .(col1)]

DT1
#    col1 col_a col_b
# 1:    a     a  <NA>
# 2:  a_b     a     b
DT2
#    col1 col_a col_b
# 1:    a     a     a
# 2:  a_b     a     b

# Output of sessionInfo()

R version 4.0.4 (2021-02-15)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19041)

Matrix products: default

locale:
[1] LC_COLLATE=French_France.1252  LC_CTYPE=French_France.1252   
[3] LC_MONETARY=French_France.1252 LC_NUMERIC=C                  
[5] LC_TIME=French_France.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] data.table_1.14.0

loaded via a namespace (and not attached):
[1] compiler_4.0.4 tools_4.0.4
@mt1022
Copy link

mt1022 commented Apr 15, 2021

Here are the links to the related SO posts:
https://stackoverflow.com/q/67091535/3926543
https://stackoverflow.com/q/67090605/3926543

@ben-schwen
Copy link
Member

Might be a duplicate of #4022 or #3256

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants