1

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:

enter image description here

Any ideas?

4

1 回答 1

2

你可能正在寻找这个。

首先,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>
于 2019-02-18T10:52:49.297 回答