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
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With