首页 > 解决方案 > 如何从 R 中的多个集合中创建一个多重集合?

问题描述

我有多个集合,我想在 R 中构建他们的多个集合。有什么解决方案吗?例如,我有 3 套:

set1 <- c(1,3,6)
set2 <- c(1,2,6,7,9)
set3 <- c(1,3,7)

我想要一个像

multiset = {1:3,2:1,3:2,6:2,7:2,9:1}

where1:3表示该元素1重复3多次。

标签: rsetmultiset

解决方案


Does the following what you want?

set1 <- c(1,3,6)
set2 <- c(1,2,6,7,9)
set3 <- c(1,3,7)

tb <- table(c(set1, set2, set3))
paste(names(tb), m[,1], collapse=",", sep=":")

Edit

Following the comment, that the output should be manipulatable, one can easily put it in a matrix:

tb <- table(c(set1, set2, set3))

mat <- cbind(no=names(tb), freq=tb)

And if needed, convert the character columns to numeric:

apply(mat, 2, as.numeric)
#>      no freq
#> [1,]  1    3
#> [2,]  2    1
#> [3,]  3    2
#> [4,]  6    2
#> [5,]  7    2
#> [6,]  9    1

推荐阅读