Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

Let say, for instance, I am having the following table: 

dt <- data.table(a = 1:3, b = 4:6, a = 7:9)

# dt

   a b a

1: 1 4 7

2: 2 5 8

3: 3 6 9

And I want to perform the subset of the data.table so that all columns with the name a get selected. The following code only provides the first match.

dt[, "a", with = F]

   a

1: 1

2: 2

3: 3

1 Answer

0 votes
by (108k points)

For achieving your goal output, you just have to pass a logical vector for selecting the columns.

library(data.table)

dt[, names(dt) == 'a', with = FALSE]

#   a a

#1: 1 7

#2: 2 8

#3: 3 9

If you are a beginner and want to know more about R then do check out the R programming tutorial.

Browse Categories

...