有没有好的方法来获取 data.table 中 i - 参数的整个长度?

问题描述 投票:0回答:1

有没有一种好方法可以找出 data.table 中正在处理的整个数据的长度,就像使用

.N
返回组的长度一样?

我举个例子:

library(data.table)
dt <- as.data.table(iris)
dt$Species[1:10] <- NA
dt[
  !is.na(Species),
  list(
    proportion = .N / 140,
    sepalwidthmean = mean(Sepal.Width)
  ),
  by = Species
]
dt[
  !is.na(Species),
  list(
    proportion = .N / sum(!is.na(dt$Species)),
    sepalwidthmean = mean(Sepal.Width)
  ),
  by = Species
]

如您所见,需要相当多的输入才能获得 140 (150-10),这本质上是多余的(已在我的查询的 i 参数中完成)。

我的做法让我感觉有点可怕,因为通常情况下,data.table 会查看列的名称,而不是全局变量范围的名称。所以

dt$dt <- "dt"
dt[
  !is.na(Species),
  list(
    proportion = .N / sum(!is.na(dt$Species)),
    sepalwidthmean = mean(Sepal.Width),
    lalala = mean(`dt$Species`)
  ),
  by = Species
]

你会得到

Error in dt$Species : $ operator is invalid for atomic vectors
。有没有一种优雅的方法可以做到这一点?

感觉有点像魔法,通常情况下,一切都会正常进行:

dt$mean <- "mean"
dt[,mean(Sepal.Length)]

给出

5.843333
而不是错误。所以也许你可以明白为什么我想要一种比我目前使用的方法更好的方法。

r data.table
1个回答
0
投票
dt[!is.na(Species), .(sepalwidthmean = mean(Sepal.Width), .N), by=Species
 ][, proportion := N/sum(N)][]

      Species     N sepalwidthmean proportion
       <fctr> <int>          <num>      <num>
1:     setosa    40         3.4575  0.2857143
2: versicolor    50         2.7700  0.3571429
3:  virginica    50         2.9740  0.3571429
© www.soinside.com 2019 - 2024. All rights reserved.