我的数据框看起来像这样:
Row ID1 ID2 Colors1 Colors2
1 1 2 Green, Blue Red, Orange
2 1 3 Green, Orange Orange, Red
我想创建一个计算,告诉我Colors1和Colors2之间的颜色计数。期望的结果如下:
Row ID1 ID2 Colors1 Colors2 Common
1 1 2 Green, Blue, Purple Green, Purple 2 #Green, Purple
2 1 3 Green, Orange Orange, Red 1 #Orange
答案 0 :(得分:2)
另一种方法是将第一列视为正则表达式,以便在第二列中进行搜索,并使用“stringi”包来促进模式的矢量化搜索。
df <- structure(list(Colors1 = c("Green, Blue, Purple", "Green, Blue",
"Green, Blue, Purple"), Colors2 = c("Green, Purple", "Green, Purple",
"Orange, Red")), .Names = c("Colors1", "Colors2"), row.names = c("2",
"21", "3"), class = "data.frame")
df
# Colors1 Colors2
# 2 Green, Blue, Purple Green, Purple
# 21 Green, Blue Green, Purple
# 3 Green, Blue, Purple Orange, Red
library(stringi)
stri_extract_all_regex(df$Colors2, gsub(", ", "|", df$Colors1))
# [[1]]
# [1] "Green" "Purple"
#
# [[2]]
# [1] "Green"
#
# [[3]]
# [1] NA
stri_count_regex(df$Colors2, gsub(", ", "|", df$Colors1))
# [1] 2 1 0
基本上,我在那里做的是使用gsub
将“Colors1”列转换为正则表达式搜索模式,看起来像"Green|Blue|Purple"
而不是"Green, Blue, Purple"
,并将其用作我在上面演示的每个“stringi”函数中的搜索模式。
答案 1 :(得分:1)
您可以使用:
col1 <- strsplit(df$Colors1, ", ")
col2 <- strsplit(df$Colors2, ", ")
df$Common <- sapply(seq_len(nrow(df)), function(x) length(intersect(col1[[x]], col2[[x]])))
df <- data.frame(Colors1 = c('Green, Blue', 'Green, Blue, Purple'), Colors2 = c('Green, Purple', 'Orange, Red'), stringsAsFactors = FALSE)
col1 <- strsplit(df$Colors1, ", ")
col2 <- strsplit(df$Colors2, ", ")
df$Common <- sapply(seq_len(nrow(df)), function(x) length(intersect(col1[[x]], col2[[x]])))
df
# Colors1 Colors2 Common
# 1 Green, Blue Green, Purple 1
# 2 Green, Blue, Purple Orange, Red 0