r - 如何从数据框中提取最后的、唯一的和连续的值
问题描述
我已经从 .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 中的连续值,而不仅仅是删除最后一行?
解决方案
定义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
推荐阅读
- php - 用于登录的多个数据库请求
- elasticsearch - 是否有 html_strip 过滤器的 JSON 等价物?
- reactjs - 当我使用 flatList 时,ref.current 总是用反应钩子返回 null
- scala - getClass.getFields 从 Scala 反射库返回字段,而不是从包中返回字段
- javascript - 当外部源更新文本时,防止 ckeditor 触发 set 回调
- c# - 使用 1 次后如何取消动画?
- javascript - 根据元素内的类显示功能 - Javascript vanilla
- python - 使用 python 文件作为 qt5 文件
- c++ - 使第二类的构造函数成为第一类中的友元函数
- r - 变量比样本多得多的网络模型