在数据表中重新分类选择列 [英] Reclassify select columns in Data Table

查看:136
本文介绍了在数据表中重新分类选择列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用向量化操作更改数据表中所选变量的类别。我是新的data.table语法,我试图尽可能多地学习。我现在的问题是基本的,但它会帮助我更好地理解数据表的思维方式!

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.

感谢您的时间。

推荐答案

我认为@ SimonO101做了大部分的工作

I think that @SimonO101 did most of the Job

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

您可以使用:= 魔术

这篇关于在数据表中重新分类选择列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆