r - R - 条件标签,但不是第一个
问题描述
我有一个具有以下结构的数据集(虚拟数据,但与我所拥有的类似):
data <- data.frame(msg = c("this is sample 1", "another text", "cats are cute", "another text", "", "...", "another text", "missing example case", "cats are cute"),
no = c(1, 15, 23, 9, 7, 5, 35, 67, 35),
pat = c(0.11, 0.45, 0.3, 0.2, 0.6, 0.890, 0.66, 0.01, 0))
我对专栏很感兴趣msg
。我需要用新列或在新列(即)中标记每一行。此标签必须在以下条件下完成:TRUE
FALSE
usable
- 如果
msg
单元格为空(NA 或空字符串)=> FALSE - 如果
msg
单元格只有符号(没有字母没有数字)=> FALSE - 如果
msg
已经存在(假设行按升序排列)=> FALSE。请注意,第一个条目将为 TRUE,而重复的条目将为 FALSE。我不关心其他列(它们与比较无关),但在我的最终结果中,我需要拥有所有列。
我用 for 做了一个非常冗长的方法,但我正在寻找更短且性能更好的方法,因为原始数据集很长。
解决方案
一个整洁的选择。请注意,这map2_lgl
是为了方便而不是速度。
library(dplyr)
library(purrr)
library(stringr)
data %>%
mutate(id = row_number(),
usable = map2_lgl(msg, id,
~ case_when(is.na(.x) | .x == '' ~ F,
!str_detect(.x, '\\w') ~ F,
.x %in% msg[1:.y-1] ~ F,
T ~ T))) %>%
select(-id)
# msg no pat usable
# 1 this is sample 1 1 0.11 TRUE
# 2 another text 15 0.45 TRUE
# 3 cats are cute 23 0.30 TRUE
# 4 another text 9 0.20 FALSE
# 5 7 0.60 FALSE
# 6 ... 5 0.89 FALSE
# 7 another text 35 0.66 FALSE
# 8 missing example case 67 0.01 TRUE
# 9 cats are cute 35 0.00 FALSE
推荐阅读
- unit-testing - 通过 .NET SDK 模拟调用 Azure 认知搜索的任何工作示例?
- r - 添加一个虚拟因子以标准化多个图中的 x 轴
- amazon-web-services - AWS ec2 RequestSpotInstances - InvalidSubnetID.NotFound 在传递逗号分隔的子网 ID 时
- ros - 为什么不是所有五个防水 JSN-SR04T 超声波距离传感器都将 ping 传送到 ROS Noetic?
- python - Python中如何将YOLO格式注解转换为x1,y1,x2,y2坐标?
- python - SikuliLibrary 图像识别功能在 Windows 上不起作用
- node.js - Visual Studio 构建 njsproj Node.js 项目,即使自上次构建以来没有任何更改
- javascript - RxJs:当全部取消订阅时,中止延迟和共享的 observable
- javascript - 让引导程序使用 gridstack 小部件大小来调整大小?
- c# - 当输入记录数 > 1000 条记录时有效调用 GetByIds(MS Graph API 方法)