检测字符串是否以特定顺序出现

时间:2019-06-17 06:34:23

标签: r string count stringr detect

我想计算出我的学生可以陈述5个特定单词的次数,以及针对学生的回答(单词顺序正确)的子集/过滤器的次数。 正确的顺序=绿色,黄色,橙色,红色,黑色。 所有数据均为小写且没有标点符号:

#     Student responses
Id    Data$Colors
1     green yellow orange red black
2     yellow green orange red black
3     red violet pink black
4     purple green orange red black
5     blue pink yellow scarlet   

我想要的输出是:

#   Student responses
Id  Data$Colors                                Data$Count   Data$CorrOrder
1   green yellow orange red black              5            TRUE
2   yellow green orange red blacks             4            FALSE
3   red violet pink black                      2            TRUE
4   purple green orange red black              4            TRUE
5   blue pink yellow brown                     1            NA
6   green yellow orange red very red black     4*           TRUE

-1点重复。 通过执行此操作,我已经能够获得计数列

Data <- c("\\bgreen\\b", "\\byellow\\b", "\\borange\\b", "\\bred\\b", "\\bblack\\b")

Data$Count<- str_count(Data$Colors, paste(Data, collapse = '|'))

但是,对于重复的正确颜色(如ID 6),这不会减去。

任何人都知道如何生成Data$CorrOrder吗?

2 个答案:

答案 0 :(得分:2)

使用tidyverse我们可以分别获得CountCorrOrder。为了获得Count,我们首先在空间上分割Colors,然后为每种颜色创建separate_rows,以便于比较值。然后,我们计算总数unique中每个Colors中有Id all_colors个中有多少duplicated,由于我们想给每个重复的值-1,因此我们将其减去每组中all_colors <- c("green", "yellow", "orange", "red", "black") library(tidyverse) df1 <- df %>% left_join(df %>% separate_rows(Colors, sep = "\\s+") %>% group_by(Id) %>% summarise(count = max(sum(all_colors %in% unique(Colors)) - sum(duplicated(Colors)), 0))) 值的数量,得出总分。

all_colors

为了获得正确的顺序,我们再次将颜色分成不同的行,仅保留TRUE中的颜色并删除重复项,并检查颜色出现的顺序是否一直在增加,并分配逻辑FALSE / { {1}}相应地值。

df1 %>%
   left_join(df1 %>%
              separate_rows(Colors, sep = "\\s+") %>%
              group_by(Id) %>%
              filter(Colors %in% all_colors & !duplicated(Colors)) %>%
              summarise(new = if (n() == 1) NA 
              else all(diff(na.omit(match(Colors, all_colors))) > 0)))

#  Id                                 Colors CorOrder Count
#1  1          green yellow orange red black     TRUE     5
#2  2         yellow green orange red blacks    FALSE     4
#3  3                  red violet pink black     TRUE     2
#4  4          purple green orange red black     TRUE     4
#5  5                 blue pink yellow brown       NA     1
#6  6 green yellow orange red very red black     TRUE     4

答案 1 :(得分:1)

首先,如果将值视为ordered因子,则可以使用is.unsorted来检查它们是否已排序而不进行排序:

colorder <- c("green", "yellow", "orange", "red", "black")

spl <- lapply(strsplit(dat$Colors, "\\s+"), ordered, levels=colorder)
cnt <- sapply(spl, function(x) length(unique(na.omit(x))) - sum(tabulate(x) > 1) )
cnt
#[1] 5 4 2 4 1 4
out <- !sapply(spl, is.unsorted, na.rm=TRUE)
out[cnt == 1] <- NA
out
#[1]  TRUE FALSE  TRUE  TRUE    NA  TRUE