Reclassify Selection Columns in a Data Table

I want to change the class of selected variables in a data table using a vectorized operation. I am new to data.table syntax and try to learn as much as possible. I am now a basic question, but it will help me better understand the way data is displayed!

A similar question was asked here ! However, the solution seems to relate to reclassifying only one column or all columns. My question is unique across multiple columns.

### Load package require(data.table) ### Create pseudo data data <- data.table(id = 1:10, height = rnorm(10, mean = 182, sd = 20), weight = rnorm(10, mean = 160, sd = 10), color = rep(c('blue', 'gold'), times = 5)) ### Reclass all columns data <- data[, lapply(.SD, as.character)] ### Search for columns to be reclassed index <- grep('(id)|(height)|(weight)', names(data)) ### data frame method df <- data.frame(data) df[, index] <- lapply(df[, index], as.numeric) ### Failed attempt to reclass columns used the data.table method data <- data[, lapply(index, as.character), with = F] 

Any help would be greatly appreciated. My data is big, and so using regular expressions to create a vector of column numbers for reclassification is necessary.

Thank you for your time.

+6
source share
3 answers

I think @ SimonO101 did most of the job

 data[, names(data)[index] := lapply(.SD, as.character) , .SDcols = index ] 

You can use magic :=

+8
source

You can avoid the overhead of building .SD inside j by using set

 for(j in index) set(data, j =j ,value = as.character(data[[j]])) 
+9
source

You just need to use .SDcols with your index vector (I found out today!), But that just returns a data table with reclassified columns. @ Dickoa's answer is what you are looking for.

 data <- data[, lapply(.SD, as.character) , .SDcols = index ] sapply(data , class) id height weight "character" "character" "character" 
+4
source

Source: https://habr.com/ru/post/943662/


All Articles