Home > Software design >  Loop through dynamic columns
Loop through dynamic columns

Time:11-01

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.

CodePudding user response:

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")
  • Related