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

add support for a list of selection expressions in .SDcols #6624

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

r2evans
Copy link
Contributor

@r2evans r2evans commented Nov 25, 2024

Closes #6619.

This adds the ability to select columns with more than one type of expression.

BLUF:

DT = data.table(int1=1L, int2=2L, chr1="A", chr2="B", num1=1, num2=2, lgl=TRUE)
DT[, .SD, .SDcols=.(is.numeric, patterns("2$"), "lgl")]
#     int1  int2  num1  num2   chr2    lgl
#    <int> <int> <num> <num> <char> <lgcl>
# 1:     1     2     1     2      B   TRUE

Justification

Traditional column-selection allows selection by:

  • column names
  • integers (column index)
  • patterns(..)
  • function call, e.g., is.numeric

In order to combine two or more of these in traditional methods, we would need to first run the functions or patterns individually and then either cbind them all or do similar efforts to collect column names and pass those into a single .SDcols=cols argument.

If we want to select all numeric columns, those ending in "2", and the "lgl" column, then we would need to do one of these methods:

cbind(DT[, .SD, .SDcols=is.numeric], DT[, .SD, .SDcols=patterns("2$")], DT[, .SD, .SDcols="lgl"])
#     int1  int2  num1  num2  int2   chr2  num2    lgl
#    <int> <int> <num> <num> <int> <char> <num> <lgcl>
# 1:     1     2     1     2     2      B     2   TRUE

This naive approach results in duplicate selections in int2 and num2.

Another approach might be:

cols <- unique(c(names(which(sapply(DT, is.numeric))), grep("2$", names(DT), value=TRUE), "lgl"))
DT[, .SD, .SDcols=cols]
#     int1  int2  num1  num2   chr2    lgl
#    <int> <int> <num> <num> <char> <lgcl>
# 1:     1     2     1     2      B   TRUE

While the latter is not egregious, my patch enables an inline all-at-once selection that seems intuitive

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

Successfully merging this pull request may close these issues.

FR: .SDcols support list of expressions
1 participant