首页 > 解决方案 > 如何从数据框中提取最后的、唯一的和连续的值

问题描述

我已经从 .txt 文件中提取了某些字符串和相应的行到一个数据框中。如何从中提取最后一个唯一的连续值到一个新的数据框中?

这是示例df:

```
Line <- c(seq(from = 1, length.out = 9, by = 421), 4211)
string <- rep(c("Plate 1", "Plate 2", " Plate 3"))
Text <- c(rep(string, length.out = 9), "Plate 3")

df <- data.frame(Line = Line,
                 Text = Text )
```

这就是我想要得到的:

```

my_df <- data.frame(Line = c(2527, 2948, 3369),
                    Text = c("Plate 1", "Plate 2", "Plate 3"))
```

我试图像这样切片它:

```
df %>% group_by(Text) %>% slice(unique(last(n())))
```

但这会得到带有错误行的副本。

有没有办法查看 R 中的连续值,而不仅仅是删除最后一行?

标签: r

解决方案


定义n为 的长度,string然后用于rollapplyr查找等于 的序列右端的索引trimws(string)。取最后一个并使用seq从其右端点推导出相应的序列,然后最后为其下标df

library(zoo)

n <- length(string)
r <- rollapplyr(as.character(df$Text), n, identical, trimws(string), fill = FALSE)
df[seq(to = tail(which(r), 1), length = n), ]

给予:

  Line    Text
7 2527 Plate 1
8 2948 Plate 2
9 3369 Plate 3

推荐阅读