注意:这是对上一个问题的直接跟进。
我有一个非常长的数据框,由两列组成,我正在将它们用作函数的参数,使用mapply查找第三列的值,如下所示:
df$3rd <- mapply(myfunction, A=df$1st, B=df$2nd)
当myfunction
有参数A和B时。虽然这对于小数据集非常有效,但对于大数据集则会停滞,因此我认为解决问题的好方法是使用ddply
应用此函数。我不知道ddply
是否是解决这个问题的最佳方法,但我也遇到了一些语法问题。所以任何建议都将不胜感激。
这是我正在尝试的:
> df$3rd <- ddply(df, .(1st), function(x) x$3rd <-
> mapply(myfunction, A=x$1st, B=df$second))
这是我收到的错误信息:
Error in `$<-.data.frame`(`*tmp*`, "n", value = c(1L, 1L, 1L, 1L, 1L, :
replacement has 112 rows, data has 16
编辑:
鉴于答案和评论,我在下面发布了一个小的可重现示例-它是上一个问题的答案之一。但是,如下面的评论者所指出的那样,ddply可能不是正确的方法。我现在正在尝试Ramnath的解决方案。
library(reshape2)
foo <- data.frame(x = c('a', 'a', 'a', 'b', 'b', 'b'),
y = c('ab', 'ac', 'ad', 'ae', 'fx', 'fy'))
bar <- data.frame(x = c('c', 'c', 'c', 'd', 'd', 'd'),
y = c('ab', 'xy', 'xz', 'xy', 'fx', 'xz'))
nShared <- function(A, B) {
length(intersect(with(foo, y[x==A]), with(bar, y[x==B])))
}
# Enumerate all combinations of groups in foo and bar
(combos <- expand.grid(foo.x=unique(foo$x), bar.x=unique(bar$x)))
# Find number of elements in common among all pairs of groups
combos$n <- mapply(nShared, A=combos$foo.x, B=combos$bar.x)
# Reshape results into matrix form
dcast(combos, foo.x ~ bar.x)
# foo.x c d
# 1 a 1 0
# 2 b 0 1
mapply
和expand.grid
函数。 - Ramnath