1

Say I have this df

require(data.table)

df <- data.table(a = 1:2
                 , b = 3:4
                 , c = 5:6
                 ); df

   a b c
1: 1 3 5
2: 2 4 6

and I wanted to fetch 2 columns at a time e.g. c('a', 'b') then c('a', 'c'). I tried:

x <- c('b', 'c')

for (i in x)
{
  print( df[, c('a', i)]  )
}

instead of returning a data table with the specified columns it only returned the vector of the specified column names:

[1] "a" "b"
[1] "a" "c"

What am I doing wrong? Thank you.

1 Answer 1

4

1) with Using the input shown reproducibly in the Note at the end add with=FALSE

for (i in x) {
  print( df[, c('a', i), with = FALSE]  )
}

giving:

   a b
1: 1 3
2: 2 4
   a c
1: 1 5
2: 2 6

2) dot dot This would also work and gives the same result.

for (i in x) {
  cn <- c('a', i)
  print( df[, ..cn]  )
}

3) .SD We can use .SD with .SDcols like this:

for (i in x) {
  print( df[, .SD, .SDcols = c("a", i)]  )
}

4) subset We could use the subset function. It has a data.table method.

for (i in x) {
  print( subset(df, select = c('a', i)) )
}

5) data.frame Also if you use a data frame rather than a data.table then it would work without any of the above.

DF <- as.data.frame(df)
for (i in x) {
  print( DF[, c('a', i)]  )
}

giving:

  a b
1 1 3
2 2 4
  a c
1 1 5
2 2 6

Note

The question was missing the library statement and definition of x so we used the following.

library(data.table)

df <- data.table(a = 1:2
                 , b = 3:4
                 , c = 5:6
                 ); df

x <- c("b", "c")
Sign up to request clarification or add additional context in comments.

5 Comments

To make it slightly more robust, I would adapt it to this: for (i in 2:length(names(df))) { print(df[, c(1, i), with = F]) }
I was aware of the .. method but wondered if there was a method that did not necessitate creating another vector. with = F was what I was after Thank you !
Added .SD alternative.
@MerijnvanTilborg Yes, this works too. Though is more situation specific. e.g. column indexing by number
@G.Grothendieck Very true. I too knew of .SD but had only used in context of apply. Need to think outside the box more

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.