data.table列的类 [英] Class of data.table column

查看:86
本文介绍了data.table列的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何确定data.table dt 中给定字符向量 w



可重现的示例:

  dt< -  data.table(matrix(1:10,2))
w< - V1

当您直接指定列时,它会返回向量,以便您可以得到它的类:

  dt [,V1] 
[1] 1 2
> class(dt [,V1])$ ​​b $ b [1]integer

一个字符向量,而是返回一列数据表:

 > dt [,w,with = FALSE] 
V1
1:1
2:2
> class(dt [,w,with = FALSE])
[1]data.tabledata.frame

我已经尝试了下面的解决方案,但是肯定有更好的方法:

  dt [,eval(parse(text = paste0(class(,w,)))


b $ b

这两个问题:


  1. 有更好的(更简洁)得到单列的类通过评估在data.table环境中对 class 的调用,放弃上述解决方案获得的速度?

  2. 一种获取所有列的类的向量的方法,类似 sapply(myDataFrame,class)

$ b $


  1. class(dt [[w]])

  2. sapply(dt,class)

另外,做2,然后子集化适用于1: sapply(dt,class)[w ]


I'd like to know how to ascertain the class of a column in a data.table dt given a character vector w.

Reproducible example:

dt <- data.table(matrix(1:10, 2))
w <- "V1"

When you specify a column by name directly, it returns the vector so that you can get its class:

> dt[,V1]
[1] 1 2
> class(dt[,V1])
[1] "integer"

Specify it as a character vector, however, and it instead returns a one-column data.table:

> dt[,w,with=FALSE]
   V1
1:  1
2:  2
> class(dt[,w,with=FALSE])
[1] "data.table" "data.frame"

I've sort of munged my way to the following solution, but surely there's a better way:

dt[,eval(parse(text=paste0("class(",w,")")))]

So two questions:

  1. Is there a better (more concise) to get the class of a single column (withoout giving up the speed that the above solution gains by evaluating the call to class in the environment of the data.table?
  2. Is there a way to get a vector of the classes of all columns, analagous to sapply( myDataFrame, class) ?

解决方案

These seem to work in the way you want:

  1. class(dt[[w]])
  2. sapply(dt,class)

Also, doing 2 and then subsetting works for 1: sapply(dt,class)[w].

这篇关于data.table列的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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