r - duplicates in agrep function
问题描述
I have the following code:
x <- data.frame("SN" = 1:2, "Name" = c("aaa","bbb"))
y <- data.frame("SN" = 1:2, "Name" = c("aa1","aa2"))
x$partials<- as.character(sapply(x$Name, agrep, y$Name,max.distance = 1,value=T))
x
The output is the following:
> x
SN Name partials
1 1 aaa c("aa1", "aa2")
2 2 bbb character(0)
However I am expecting the following output:
Any ideas?
解决方案
你可能正在寻找这个。
首先,sapply()
如果character(0)
. 为了防止这种情况,如果你真的想要这个,你可以说它是NA
或文本。"character(0)"
z <- setNames(sapply(x$Name, function(a) {
ag <- agrep(a, y$Name, max.distance=1, value=TRUE)
if (identical(ag, character(0))) NA # set to "character(0)" at will
else ag
}), x$Name)
然后,将您得到的列表转换为矩阵。
z <- do.call(rbind, z)
我们需要melt()
它来获得正确的格式。一个好方法是使用data.table
.
library(data.table)
z <- setNames(melt(z)[-2], c("Name", "partials"))
现在,我们只需将 x 与新数据合并以获得结果,确保z
.
res <- merge(x, unique(z))[c(2, 1, 3)]
> res
SN Name partials
1 1 aaa aa1
2 1 aaa aa2
3 2 bbb <NA>
推荐阅读
- plotly - 使用 Plotly 生成有角度的条形图(来自 Dash 的风险分析)
- arrays - 在文档内的firebase数据库中合并新对象
- html - Next.js 的标签和 HTML 原生的标签一样吗
? - c++ - 如何使用 Visual C++ 构建 wxWidgets
- reactjs - 记忆对象数组的状态
- swift - 使用相同的视图添加和编辑 CoreData 对象
- python - PySimpleGui 树添加带有事件的元素以减少启动时间
- python - Python KivyMD 图标未显示在 Andriod 应用程序上
- php - 如何在 PHP Laravel 7.3.x 中将“foreach 循环”转换为“for 循环”
- ruby-on-rails - Rails Carrierwave Unpermitted 参数