为什么mutate(row_number())对于data.tables失败? [英] Why does mutate(row_number()) fail for data.tables?
问题描述
当我尝试在数据表上使用 dplyr
中的 row_number()
时,将引发错误。例如:
When I try to use row_number()
from dplyr
on a data.table, it throws an error. Here's an example:
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
任何想法为何
推荐答案
dplyr :: row_number()
函数有一个强制性参数,它应该是您要为其做行号的列的名称。
The dplyr::row_number()
function has a mandatory parameter, which should be the name of the column that you want to do a row number for.
在您的示例中,您应该这样写:
In your example, you should have written it like this:
library(dplyr)
library(data.table)
mine <- data.table(a = 1:10) %>%
mutate(row_number(a))
因为 a
是您要为其添加 row_number()
的列的名称。没有这个,R就会抛出错误参数 x丢失,并且没有默认值
。
Because a
is the name of the column that you want to add the row_number()
for. Without this, then R throws the error argument "x" is missing, with no default
.
但是,我建议使用 tibble :: rowid_to_column()
函数。
However, I'd suggest using the tibble::rowid_to_column()
function. It's cleaner.
library(dplyr)
library(data.table)
library(tibble)
mine <- data.table(a = 1:10) %>%
rowid_to_column()
我希望能帮上忙。
这篇关于为什么mutate(row_number())对于data.tables失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!