bkt*_*619 5 string r dplyr tidyverse
我有一个tbl_df并希望看到两个字符串之间匹配单词的百分比.
数据如下所示:
# A tibble 3 x 2
X Y
<chr> <chr>
1 "mary smith" "mary smith"
2 "mary smith" "john smith"
3 "mike williams" "jack johnson"
Run Code Online (Sandbox Code Playgroud)
期望的输出(按行以任意顺序排列):
# A tibble 3 x 3
X Y Z
<chr> <chr> <dbl>
1 "mary smith" "mary smith" 1.0
2 "mary smith" "john smith" 0.50
3 "mike williams" "jack johnson" 0.0
Run Code Online (Sandbox Code Playgroud)
一个选项是在将列按空格分隔并除以后base R检查length常用单词 ( intesect)的splitlength
df1$Z <- mapply(function(x, y) length(intersect(x, y))/length(x),
strsplit(df1$X, " "), strsplit(df1$Y, " "))
df$Z
#[1] 1.0 0.5 0.0
Run Code Online (Sandbox Code Playgroud)
或者在 中tidyverse,我们可以使用map2并应用相同的逻辑
library(tidyverse)
df1 %>%
mutate(Z = map2(strsplit(X, " "), strsplit(Y, " "), ~
length(intersect(.x, .y))/length(.x)))
# X Y Z
#1 mary smith mary smith 1
#2 mary smith john smith 0.5
#3 mike williams jack johnson 0
Run Code Online (Sandbox Code Playgroud)
df1 <- structure(list(X = c("mary smith", "mary smith", "mike williams"
), Y = c("mary smith", "john smith", "jack johnson")), .Names = c("X",
"Y"), class = "data.frame", row.names = c("1", "2", "3"))
Run Code Online (Sandbox Code Playgroud)