1

我正在尝试比较X存储在两个数据帧 ( foo, ) 中的变量集 ( bar)。每个X都是一个唯一的自变量,最多有 10 个Y与之相关的值。我想通过比较Y它们共有的值的数量来比较每个 foo.X 和每个 bar.X - 所以输出可以是一个矩阵,其轴的长度为 foo.x 乘以 bar.x。

这个 foo 和 bar 的简单示例想要返回一个 2x2 矩阵,将 a,b 与 c,d 进行比较:

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'))

编辑:


我将以下代码留给其他新手学习(for 循环是有效的,但可能非常次优),但下面的两个解决方案是有效的。特别是 Ramnath 对 data.table 的使用在处理非常大的数据帧时非常有效。

将数据帧存储为列表,其中使用stack函数存储 y 的值

foo.list <- dlply(foo, .(x), function(x) stack(x, select = y))
bar.list <- dlply(bar, .(x),function(x)  stack(x, select = y))

编写一个函数来比较两个堆叠列表中的成员资格

comparelists <- function(list1, list2) {
  for (i in list1){ 
    for (j in list2){
      count <- 0
      if (i[[1]] %in% j[[1]]) count <- count + 1
    }
  }
  return count
  }

写一个输出矩阵

output.matrix <- matrix(1:length(foo.list), 1:length(bar.list))
for (i in foo.list){
  for (j in bar.list){
    output.matrix[i,j] <- comparelists(i,j)

    }

}

4

2 回答 2

4

必须有一百种方法来做到这一点;这是我感觉相对简单的一个:

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'))

# Create a function that counts the number of common elements in two groups
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)))
#   foo.x bar.x
# 1     a     c
# 2     b     c
# 3     a     d
# 4     b     d

# 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
于 2012-01-05T21:12:45.823 回答
3

这是一个更简单的方法,使用merge

library(reshape2)
df1 <- merge(foo, bar, by = 'y')
dcast(df1, x.x ~ x.y, length)

  x.x c d
1   a 1 0
2   b 0 1

编辑。使用data.table. 这是代码

foo_dt <- data.table(foo, key = 'y')
bar_dt <- data.table(bar, key = 'y')
df1 <- bar_dt[foo_dt, nomatch = 0]
于 2012-01-07T00:30:54.497 回答