Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data.table delete the columns that end in "_nd"

Tags:

r

data.table

I have a datatable in R

I'd like to delete the columns that end in "_nd".

My dt:

I'd like

I want the opposite of this script

dt[,.SD, .SDcols = patterns("_nd")] 

Thank you for your help

like image 230
Mathieu L Avatar asked Apr 24 '20 13:04

Mathieu L


2 Answers

One approach could be to grep within J.

dt[,names(dt)[grep("_nd",names(dt))] := NULL]

The benefit of this approach is that it removes by reference.

like image 181
Ian Campbell Avatar answered Sep 25 '22 22:09

Ian Campbell


I'll do :

library(data.table)

dt <- data.table(var1 = 1:10, var1_n = 1:10, var2_n = 1:10)
dt
#     var1 var1_n var2_n
#    <int>  <int>  <int>
# 1:     1      1      1
# 2:     2      2      2
# 3:     3      3      3
# 4:     4      4      4
# 5:     5      5      5
# 6:     6      6      6
# 7:     7      7      7
# 8:     8      8      8
# 9:     9      9      9
# 10:    10     10     10

to_rm <- grep("_n$", names(dt), value = TRUE)
dt[, (to_rm) := NULL]
dt
#     var1
#    <int>
# 1:     1
# 2:     2
# 3:     3
# 4:     4
# 5:     5
# 6:     6
# 7:     7
# 8:     8
# 9:     9
# 10:    10

or maybe simpler:

dt <- data.table(var1 = 1:10, var1_n = 1:10, var2_n = 1:10)
dt[, .SD, .SDcols = grep("_n$", names(dt), invert = TRUE, value = TRUE)]

This will also work:

dt <- data.table(var1 = 1:10, var1_n = 1:10, var2_n = 1:10)
to_keep <- grep("_n$", names(dt), invert = TRUE, value = TRUE)
dt[, ..to_keep]
like image 38
Victorp Avatar answered Sep 24 '22 22:09

Victorp