将 table() 结果迭代到 matrix/data 帧中

iterating table() results into matrix/data frame

这一定很简单,但我已经苦思冥想了一会儿。请帮忙。我有一个大数据集,我可以通过 table() 从中获取各种信息。然后我想存储这些计数,以及被计数的行名。对于可重现的示例,请考虑

a <- c("a", "b", "c", "d", "a", "b")  # one count, occurring twice for a and 
                                      # b and once for c and d 
b <- c("a", "c")  # a completly different property from the dataset 
                  # occurring once for a and c
x <- table(a)
y <- table(b)  # so now x and y hold the information I seek

我如何merge/bind/whatever从 x 和 y 得到这种形式:

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

但是,我需要使用该解决方案迭代工作,在一个循环中使用 x 和 y 并获得上面请求的表格,然后添加更多 tables,希望每个都添加一列。我的许多失败尝试之一,只是为了展示我的(可能有缺陷的)逻辑,是:

member <- function (data = dfm, groupvar = 'group', analysis = kc15) {
  res<-matrix(NA,ncol=length(analysis$size)+1) #preparing an object for the results
  res[,1]<-table(docvars(data,groupvar)) #getting names and totals of groups
  for (i in 1:length(analysis$size)) { #getting a bunch of counts that I care about
    r<-table(docvars(data,groupvar)[analysis$cluster==i])
    res<-cbind(res,r) #here's the problem, trying to add each new count as a column.
  }
  res
}

因此,总而言之,上面的可重现示例意味着复制 res 和 r 中的第一列,我正在寻找(我认为)正确的解决方案而不是 cbind,这将允许添加不同的列length 但名称相似,如上例所示。 请帮助我在这上面浪费了多少时间

merge t 转置并重新转置。

res <- t(merge(t(unclass(x)), t(unclass(y)), all=TRUE))
res <- `colnames<-`(res[order(rownames(res)), 2:1], c("x", "y"))
res[is.na(res)] <- 0
res
#   x y
# a 2 1
# b 2 0
# c 1 1
# d 1 0

下面可能是一个选项,合并到数据框的"row names",从频率表转换而来:

df <- merge(as.data.frame(x, row.names=1, responseName ="x"), 
            as.data.frame(y, row.names=1, responseName ="y"), 
         by="row.names", all=TRUE)
df[is.na(df)] <- 0; df

  Row.names x y
1         a 2 1
2         b 2 0
3         c 1 1
4         d 1 0

然后,这个方法稍加修改就可以合并到你的真实数据中了。由于没有任何数据可以使用,所以我已经编造了数据。

set.seed(1234)
groupvar <- sample(letters[1:4], 16, TRUE)
clusters <- 1:4
cluster <- rep(clusters, each=4)

合并前两个表:

res <- merge(as.data.frame(table(groupvar[cluster==1]),
                           row.names=1, responseName=clusters[1]),
             as.data.frame(table(groupvar[cluster==2]),
                           row.names=1, responseName=clusters[2]),
             by="row.names", all=TRUE)

然后使用您的 for 循环合并其他人。

for (i in 3:length(clusters)) { 
  r <- table(groupvar[cluster==i])
  res <- merge(res, as.data.frame(r, row.names=1, responseName = clusters[i]), 
               by.x="Row.names", by.y="row.names", all=TRUE)
}
res[is.na(res)] <- 0

res
  Row.names X1 X2 X3 X4
1         a  1  2  0  0
2         b  1  1  2  2
3         c  0  1  1  2
4         d  2  0  1  0