下面是拆分DF成两片的答案(从中心向左和向右,重新排序左边,以便从中心到第一个值),然后使用cumsum和NA计算长度,以便cumsum一旦出现不匹配就变为NA,然后找到最高索引值不是NA来表示从中心开始的最长拉伸而没有不匹配。
sim_len <- function(df, center=floor(ncol(df)/2)) {
dfs <- list(df[, max(center, 1):1, drop=F], df[, center:ncol(df), drop=F])
df.count <- lapply(dfs, function(df) {
diff <- cumsum(ifelse(df[1, ] == df[2, ], 1, NA_integer_))
diff[max(which(!is.na(diff)))]
})
max(0L, sum(unlist(df.count)) - 1L)
}
这里是运行它(as.data.frame
企业只是从创建的字符串数据帧的一些例子。请注意,“中心”列中的最后一行计算两次,因此-1L该功能。
r1 <- "ghuytuthjilujshdftgu"
r2 <- "ghuytuthjilujshdftgu"
df1 <- as.data.frame(rbind(unlist(strsplit(r1, "")), unlist(strsplit(r1, ""))))
sim_len(df1)
# [1] 20
r1 <- "ghuytut3jilujshdftgu"
r2 <- "ghuytuthjilujshdftgu"
df2 <- as.data.frame(rbind(unlist(strsplit(r1, "")), unlist(strsplit(r2, ""))))
sim_len(df2)
# [1] 12
r1 <- "ghuytut3jilujshdftgu"
r2 <- "ghuytuthjilujxhdftgu"
df3 <- as.data.frame(rbind(unlist(strsplit(r1, "")), unlist(strsplit(r2, ""))))
sim_len(df3)
# [1] 5
r1 <- "ghuytut3xilujshdftgu"
r2 <- "ghuytuthjixujxhdftgu"
df4 <- as.data.frame(rbind(unlist(strsplit(r1, "")), unlist(strsplit(r2, ""))))
sim_len(df4)
# [1] 1
,报告左,右计数的变化。请注意,“中心”进行计数左,右,这样的总和左+右比什么报道1大原创功能:
sim_len2 <- function(df, center=floor(ncol(df)/2)) {
dfs <- list(left=df[, max(center, 1):1, drop=F], right=df[, center:ncol(df), drop=F])
vapply(dfs,
function(df) {
diff <- cumsum(ifelse(df[1, ] == df[2, ], 1, NA_integer_))
diff[max(which(!is.na(diff)))]
},
numeric(1L)
) }
sim_len2(df1)
# left right
# 10 11
sim_len2(df4, 4)
# left right
# 4 4
请提供一个可重现的例子。这是一个矩阵吗?这是一列数据框吗? –
嘿..它是一个data.frame(我更新了anser)..这有帮助吗? – user3069326
我删除我的答案,因为它不清楚你在问什么。 – agstudy