首页 > 解决方案 > 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。我需要用新列或在新列(即)中标记每一行。此标签必须在以下条件下完成:TRUEFALSEusable

我用 for 做了一个非常冗长的方法,但我正在寻找更短且性能更好的方法,因为原始数据集很长。

标签: rdataframe

解决方案


一个整洁的选择。请注意,这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

推荐阅读