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

Unable to assign columns using (names(.SD)) := #4905

Closed
skanskan opened this issue Feb 15, 2021 · 2 comments
Closed

Unable to assign columns using (names(.SD)) := #4905

skanskan opened this issue Feb 15, 2021 · 2 comments

Comments

@skanskan
Copy link

skanskan commented Feb 15, 2021

Hello.

I want to modify the columns containing a given pattern in their names.

Say I have this toy example:
myDT <- data.table(cod1=1:20, cod2=20:1, other1=rnorm(20), other2=rnorm(20))

And I want to convert the content of the columns whose name start by "cod" to factors.

With dplyr I can use this compact notation:
myDT %>% mutate(across(contains("cod"),as.factor))

With data.table I would use this:

cols <- grep("cod", names(myDT), value = T)
myDT[,(cols):= lapply(.SD, as.factor), .SDcols = cols] 

It's much longer and it generates new variables we don't need anymore.
Is there any shorter/simpler/faster alternative?

I have tried this:
myDT[, (names(.SD)) := lapply(.SD, as.factor) , .SDcols = patterns("cod")]
but it doesn't work.

@jangorecki
Copy link
Member

jangorecki commented Feb 15, 2021

There is FR for that already, and maybe even PR as well.

@MichaelChirico
Copy link
Member

duplicate of #795, will be fixed in #4163

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

3 participants