Reclassify select columns in Data Table
data.table, r
Solution
I think that @SimonO101 did most of the Job
data[, names(data)[index] := lapply(.SD, as.character) , .SDcols = index ]
You can just use the `:=` magic
Problem
I wish to change the class of selected variables in a data table, using a vectorized operation. I am new to the data.table syntax, and am trying to learn as much as possible. I now the question is basic, but it will help me to better understand the data table way of thinking! A similar question was asked here! However, the solution seems to pertain to either reclassing just one column or all columns. My question is unique to a select few 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 appreciated. My data are large and so using regular expressions to create a vector of column numbers to reclassify is necessary. Thank you for your time.