获取已删除行的索引
我必须删除数据框中的一行并获取已删除行的索引。
在实践中,我单击闪亮应用程序中表格的一行,然后使用操作按钮将其删除:
从这一行我需要索引:
这是一个示例来演示我想要做什么:
library(dplyr)
df1 <- diamonds %>%
select(1:2) %>%
slice(1:5)
carat cut
<dbl> <ord>
1 0.23 Ideal
2 0.21 Premium
3 0.23 Good
4 0.29 Premium
5 0.31 Good
从 df1 我删除 第 3 行
并获取df2
。但我需要已删除行的索引作为向量。
df2 <- df1 %>%
slice(-3)
carat cut
<dbl> <ord>
1 0.23 Ideal
2 0.21 Premium
3 0.29 Premium
4 0.31 Good
我已经尝试过:
anti_join(df1, df2) %>%
rownames_to_column("id") %>%
pull(id)
给出:
[1] "1"
预期输出
[1] "3"
I have to delete a row in a dataframe and get the index of the deleted row.
In practice I click on a row of a table in a shiny app and delete it with an action button:
From this row I need the index:
Here is an example to demonstrate what I would like to do:
library(dplyr)
df1 <- diamonds %>%
select(1:2) %>%
slice(1:5)
carat cut
<dbl> <ord>
1 0.23 Ideal
2 0.21 Premium
3 0.23 Good
4 0.29 Premium
5 0.31 Good
From df1 I delete row 3
and get df2
. But I need the index of the deleted row as vector.
df2 <- df1 %>%
slice(-3)
carat cut
<dbl> <ord>
1 0.23 Ideal
2 0.21 Premium
3 0.29 Premium
4 0.31 Good
I have tried:
anti_join(df1, df2) %>%
rownames_to_column("id") %>%
pull(id)
which gives:
[1] "1"
Expected Output
[1] "3"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们可以在“df1”中创建一个序列列
,然后只需
pull
rn
rownames_to_column
不会给出正确的行号,因为tibble
不允许使用行名称,并且它会重置每个子集上的行号,因此我们仅获得更改后的行号而不是原始行号。除了tibble
情况之外,这里slice
确实会重置,即如果我们检查其中涉及的函数,则会调用dplyr_new_data_frame
,这可能会重置行号We could create a sequence column in 'df1'
and then just
pull
thern
rownames_to_column
doesn't give the correct row number becausetibble
doesn't allow for row names and it resets the row number on each subset, thus we get only the changed row number instead of the original one. In addition to thetibble
case, here theslice
does reset i.e. if we check the functions involved in it, there is a call todplyr_new_data_frame
, which may be resetting the row number