【问题标题】:Why does mutate(row_number()) fail for data.tables?为什么 mutate(row_number()) 对 data.tables 失败?
【发布时间】:2016-02-15 20:06:48
【问题描述】:

当我尝试在 data.table 上使用 dplyr 中的 row_number() 时,会引发错误。这是一个例子:

library(dplyr)
library(data.table)
mine <- data.table(a = 1:10)
mine %>% mutate(row_number())
# Error in rank(x, ties.method = "first", na.last = "keep") : 
#   argument "x" is missing, with no default

任何想法为什么会发生这种情况?

【问题讨论】:

  • 将其转换为tbl_df 即可,即mine %&gt;% tbl_df %&gt;% mutate(rn= row_number()) 为什么不对data.table 使用data.table 方法?这可能是一个错误..
  • 好像是known issue
  • 如果你使用data.table's,为什么不用mine[, row_number := .I]
  • mine[, row_number := 1:.N, by = group]
  • @Jaap 或 mine[, rowid(group)] 在当前的开发版本(1.9.7)中。

标签: r data.table dplyr


【解决方案1】:

dplyr::row_number() 函数有一个强制参数,它应该是您要为其做行号的列的名称。

在你的例子中,你应该这样写:

library(dplyr)
library(data.table)
mine <- data.table(a = 1:10) %>% 
    mutate(row_number(a))

因为a 是您要为其添加row_number() 的列的名称。没有这个,R 会抛出错误argument "x" is missing, with no default

不过,我建议使用tibble::rowid_to_column() 函数。它更干净。

library(dplyr)
library(data.table)
library(tibble)
mine <- data.table(a = 1:10) %>% 
    rowid_to_column()

希望对你有帮助。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-05-07
  • 2023-04-07
  • 2013-02-24
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 2015-06-19
  • 2014-06-16
相关资源
最近更新 更多