0

I have a rather simple problem as it seems, which I cannot solve myself however.

Can I somehow insert or print a column name within a data table call? I have something like this in mind:

col_names = c("column1","column2")
for (col in col_names){
        datatable$col ...
}

or

col_names = c("column1","column2")
for (col in col_names){
        datatable[,col] ...
}

What I eventually would like to do is transform the variables of certain columns into ordered factors. Since there are many columns, I'm looking for a neater way as an alternative of just coding the same line 20 times with the only difference being the column name.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
laser.p
  • 105
  • 6
  • Thank you for your answer! Yeah, I'm not just trying to print them. I just edited my question to add more detail. Sorry for the insufficient specification. – laser.p Jul 21 '20 at 14:26

2 Answers2

0

Are you trying to print the just the column name or the entire column within the datatable?

You could try something like this

col_names = c("column1","column2")
for (i in seq_along(col_names)){
        print(datatable[col_names[[i]]])
}

Or if you just want the names printed.

col_names = c("column1","column2")
for (i in seq_along(col_names)){
        print(col_names[[i]])
}

Also, you might want to check out the iteration chapter in R for Data Science.

Abeaver
  • 3
  • 1
  • Thank you for your answer! Sorry, I might need to specify this in my question. But no, I actually want to perform transformations on the single columns and not just print them. – laser.p Jul 21 '20 at 14:23
  • Oh! Well then I would absolutely use tidyverse and purr functions for that. You can use ```map()``` from purr to perform functions across multiple columns. – Abeaver Jul 21 '20 at 14:33
0

Perhaps, you can try lapply with SDcols to apply a function over col_names. You can try something like this :=

library(data.table)
datatable[, (col_names) := lapply(.SD, function(x) factor(x, ordered =  TRUE)), 
             .SDcols = col_names]

Here we apply factor(x, ordered = TRUE) to each column in col_names where x is each individual column name.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213