【发布时间】:2020-03-27 12:58:52
【问题描述】:
这一定很简单,但我正在用头撞它一会儿。请帮忙。我有一个大型数据集,我通过 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
我如何合并/绑定/从 x 和 y 获取任何内容到此表单:
x. y.
a 2. 1
b 2. 0
c 1. 1
d. 1 0
但是,我需要使用该解决方案迭代地工作,在一个循环中使用 x 和 y 并获取上面请求的表单,然后添加更多表,每个表都希望添加一列。为了展示我的(可能有缺陷的)逻辑,我的许多失败尝试之一是:
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,这将允许添加不同长度的列但是类似的名称,如上例所示。 请帮我解决一下我在这上面浪费了多少时间
【问题讨论】:
-
您好,Shouda,该示例无法完全重现,因为我们没有
docvars函数和dfm数据。你能提供这些吗?可能是dput(head(dfm))。请参阅How to make a reproducible example 了解更多信息。