R 尝试对两个列联表求和-表中错误:不一致数组
我试图将两个频率/列联表相加R 尝试对两个列联表求和-表中错误:不一致数组,r,dataframe,aggregate,tidyverse,R,Dataframe,Aggregate,Tidyverse,我试图将两个频率/列联表相加 table(data$sample_idx1) + table(data$sample_idx2) 但是我越来越 表(数据$sample_idx1)+表(数据$sample_idx2)中的错误: 非共形阵列 我认为问题在于“sample_idx1”和“sample_idx”没有完全相同的组。比如说 样本_idx1 1 2 5 10 12 12 样本_idx2 3 4 6 2 1 1 我想获得如下信息: 1 2 3 4 5 6 10 12 2
table(data$sample_idx1) + table(data$sample_idx2)
但是我越来越
表(数据$sample_idx1)+表(数据$sample_idx2)中的错误:
非共形阵列
我认为问题在于“sample_idx1”和“sample_idx”没有完全相同的组。比如说
样本_idx1
1 2 5
10 12 12
样本_idx2
3 4 6
2 1 1
我想获得如下信息:
1 2 3 4 5 6
10 12 2 1 12 1
如何执行此操作?假设您有两个由
表
函数创建的命名向量,您可以将它们与c
组合:
table(sample_idx1)
#sample_idx1
# 1 2 5
#10 12 12
table(sample_idx2)
#sample_idx2
#3 4 6
#2 1 1
c(table(sample_idx1),table(sample_idx2))
# 1 2 5 3 4 6
#10 12 12 2 1 1
如果需要结果向量有序,可以使用order(names(x))
:
样本数据
sample_idx1 <- rep(c(1,2,5),c(10,12,12))
sample_idx2 <- rep(c(3,4,6),c(2,1,1))
sample_idx3 <- rep(c(3,2,6),c(2,1,1))
sample_idx1一个选项是编写一个函数,在给定列向量的情况下,将原始数据制成表格
table2 <- function(x, cols){
y <- unlist(x[cols])
table(y)
}
table2(data, c("sample_idx1", "sample_idx2"))
表2您能澄清一下您的问题吗?我看不出你是如何在你的具体例子中添加内容的。在我看来,这看起来像是在串接,但方式很奇怪。如果要按列进行串接,可以使用cbind
。如果两个表重叠,例如sample\u idx1
中有3
,则c()
不能有理想的输出。
sample_idx1 <- rep(c(1,2,5),c(10,12,12))
sample_idx2 <- rep(c(3,4,6),c(2,1,1))
sample_idx3 <- rep(c(3,2,6),c(2,1,1))
table2 <- function(x, cols){
y <- unlist(x[cols])
table(y)
}
table2(data, c("sample_idx1", "sample_idx2"))