我已经阅读过有关data.table的DataCamp课程,并且仍然对data.table [i,j,by]中j的行为感到困惑。具体来说,当我尝试使用数字索引列时(使用with=FALSE
时),我无法获取data.table以返回正确的长度值:
library(data.table) lifetech.dt=data.table(a=c(1,2,3,4,5), b=c(1,2),d=c(5,6,7,8,9)) x=colnames(lifetech.dt) length_counter=NULL
for (a in 1:length(x)){
length_counter=c(length_counter,length(lifetech.dt[,a, with=FALSE])) }
length_counter
#should return a length of 5?, instead returns a length of 1
length(lifetech.dt[,a, with=FALSE])
length(lifetech.dt[,3,with=FALSE])
#perhaps this way? But it returns 9 (the last value in col. d?
lifetech.dt[.N,d]
#want this, but without having to know the colname of column 4 is "d" is advance
length(lifetech.dt[,d])
答案 0 :(得分:0)
有两种等效的解决方案:
假设lifetech.dt有一个名为'columnA'的列
你可以做到
length(lifetech.dt[,columnA,])
或
nrow(lifetech.dt[,"columnA",with=F])
均适用于data.table 1.9.6和R 3.2.2。
所以在你的情况下,第二个解决方案应该适合你!
答案 1 :(得分:-1)
正如@frank在评论中指出的那样,这个问题与The question asked here重复。
Data.table从data.frame继承它的class = list status,因此可以用[[而不是[。因此,length(lifetech.dt[[3]])
应该有用。