太长不看版
data.table格式在调用列时, 加上逗号, 如果是字符串, 加上with=FALSE
trait = "yield"
dat[,trait,with=F]
使用oats数据集
将其转化为dat的data.table的形式
library(asreml)
data(oats)
str(oats)
library(data.table)
dat = as.data.table(oats)
str(dat)
查看数据结构, 可以看到oats是数据框data.frame, dat是data.table
> library(asreml)
> data(oats)
> str(oats)
'data.frame': 72 obs. of 6 variables:
$ Blocks : Factor w/ 6 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
$ Nitrogen: Factor w/ 4 levels "0_cwt","0.2_cwt",..: 4 3 2 1 1 2 4 3 1 2 ...
$ Subplots: Factor w/ 4 levels "1","2","3","4": 1 2 3 4 1 2 3 4 1 2 ...
$ Variety : Factor w/ 3 levels "Golden_rain",..: 2 2 2 2 3 3 3 3 1 1 ...
$ Wplots : Factor w/ 3 levels "1","2","3": 1 1 1 1 2 2 2 2 3 3 ...
$ yield : int 156 118 140 105 111 130 174 157 117 114 ...
> library(data.table)
> dat = as.data.table(oats)
> str(dat)
Classes ‘data.table’ and 'data.frame': 72 obs. of 6 variables:
$ Blocks : Factor w/ 6 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
$ Nitrogen: Factor w/ 4 levels "0_cwt","0.2_cwt",..: 4 3 2 1 1 2 4 3 1 2 ...
$ Subplots: Factor w/ 4 levels "1","2","3","4": 1 2 3 4 1 2 3 4 1 2 ...
$ Variety : Factor w/ 3 levels "Golden_rain",..: 2 2 2 2 3 3 3 3 1 1 ...
$ Wplots : Factor w/ 3 levels "1","2","3": 1 1 1 1 2 2 2 2 3 3 ...
$ yield : int 156 118 140 105 111 130 174 157 117 114 ...
- attr(*, ".internal.selfref")=<externalptr>
使用data.frame提取列
可以将性状名赋值给一个变量trait, 然后通过trait调取:
注意: data.frame默认的dat[i]提取的是第i列的内容, data.table中的dat[i]默认的是提取第一行的内容
trait = "yield"
oats[trait]
> oats[trait] %>% head()
yield
1 156
2 118
3 140
4 105
5 111
6 130
同样的方法 在data.table中报错
trait = "yield"
dat[,trait]
报错如下:
Error in `[.data.table`(dat, , trait) :
j (the 2nd argument inside [...]) is a single symbol but column name 'trait' is not found. Perhaps you intended DT[, ..trait]. This difference to data.frame is deliberate and explained in FAQ 1.1.
解决方法
因为data.table默认的是提取行, 那么在提取时前面加上逗号, 可以提取, 但是这里trait是个变量, 如果想要使用, 需要加上参数with=FALSE
trait = "yield"
dat[,trait,with=F]
正确结果:
> dat[,trait,with=F] %>% head()
yield
1: 156
2: 118
3: 140
4: 105
5: 111
6: 130