按列对数据帧进行分组,按n个元素进行匹配

时间:2018-10-18 06:57:30

标签: r string dataframe string-matching

这是我的问题。我有两个数据框。下面是它们的简化版本。

df1
ID         String
1.1        a
1.1        a
1.1        b
1.1        c
...
1.2        a 
1.2        a
1.2        c
1.2        c
...
2.1        a
2.1        n
2.1        o
2.1        o
...
2.2        a
2.2        n
2.2        n
2.2        o
...
3.1        a
3.1        a
3.1        x
3.1        x
...
3.2        a
3.2        x
3.2        a
3.2        x
...
4.1        a
4.1        b
4.1        o
4.1        o
... 
4.2        a
4.2        b
4.2        b
4.2        o

想象每个ID(例如1.1)有1000多个行。要注意的另一件事是,在具有相同编号(例如:1.1和1.2)的ID的情况下,它们非常相似。但不是彼此完全匹配。

df2
string2
a
b
a
c

df2是测试df。

我想查看哪个df1 ID最接近df2。但是我有一个非常重要的条件。我想按n个元素进行匹配。并非整个数据框都与另一个相对。

我的伪代码:

df2-elements-to-match <- df2$string2[1:n] #only the first n elements

group df1 by ID

df1-elements-to-match <- df1$String[1:n of every ID] #only the first n elements of each ID

Output a column with score of how many matches. 

Filter df1 to remove ID groups with < m score. #m here could be any number. 

Filtered df1 becomes new df1. 

n <- n+1 

df2-elements-to-match and df1-elements-to-match both slide down to the next n elements. Overlap is optional. (ex: if first was 1:2, then 3:4 or even 2:3 and then 3:4)

Reiterate loop with updated variables

If one ID remains stop loop.

这里的想法是获得预测的匹配,而不必匹配整个测试数据帧。

1 个答案:

答案 0 :(得分:0)

## minimal dfs
df1 <- data.frame(ID=c(rep(1.1, 5),
                       rep(1.2, 6),
                       rep(1.3, 3)),
                  str=unlist(strsplit("aabaaaabcababc", "")), stringsAsFactors=F)

df2 <- data.frame(str=c("a", "b", "a", "b"), stringsAsFactors=F)


## functions

distance <- function(df, query.df, df.col, query.df.col) {
  deviating <- df[, df.col] != query.df[, query.df.col]
    sum(deviating, na.rm=TRUE) # if too few rows, there will be NA, ignore NA
}

distances <- function(dfs, query.df, dfs.col, query.df.col) {
  sapply(dfs, function(df) distance(df, query.df, dfs.col, query.df.col))
}

orderedDistances <- function(dfs, query.df, dfs.col, query.df.col) {
  dists <- distances(dfs, query.df, dfs.col, query.df.col)
  sort(dists)
}

orderByDistance <- function(dfs, query.df, dfs.col, query.df.col, dfs.split.col) {
  dfs.split <- split(dfs, dfs[, dfs.split.col])
  dfs.split.N <- lapply(dfs.split, function(df) df[1:nrow(query.df), ])
  orderedDistances(dfs.split.N, query.df, dfs.col, query.df.col)
}


orderByDistance(df1, df2, "str", "str", "ID")
# 1.3 1.1 1.2 
#   1   3   3 

# 1.3 is the closest to df2!

您的问题有点像距离问题。 最小化距离=找到最相似的序列。

我在这里显示的这种距离假定在df2和df1的sub-df之间的等效位置处,偏差被计为1,等式被计为0。该总和为比较数据帧之间的unsimilarity-score-字符串序列。

orderByDistance包含dfs(df1)和查询df(df2),应比较的列以及应将其拆分dfs的列(此处为“ ID”)。 首先,它拆分dfs,然后收集每个子df的N行(用于比较的准备),然后将orderedDistances应用于每个sub.df,并确保N行(N =查询df的行数或行)。

相关问题