【问题标题】:Convert frequency vector to logical matrix将频率向量转换为逻辑矩阵
【发布时间】:2019-10-30 13:21:47
【问题描述】:

我想将频率向量(即矩阵的colSums())转换为R 中原始逻辑矩阵的可能版本之一。

类似:

    s <- c(1,2,3)
    # Some function of s
    # Example output:
         [,1] [,2] [,3]
    [1,]    0    0    1
    [2,]    1    0    0 
    [3,]    0    1    0
    [4,]    0    0    1
    [5,]    0    0    1
    [6,]    0    1    0

行的顺序并不重要。 有人可以给我一个提示吗?

编辑:行总和始终为 1。输出可以被认为是一个多项式数据集,其中每一行都反映了一个观察结果。

【问题讨论】:

  • rowSums 总是 1?
  • 什么决定了1的位置?
  • @sindri_baldur 是的,我将其添加到原始帖子中。
  • @akrun Chance 和总和。期望的输出可以被认为是一个多项式数据集,每行应该只有一个值 1,其余的值为零。但是,colsum 应该等于 s 中的值。

标签: r matrix vector


【解决方案1】:
set.seed(523)

s <- c(1, 2, 3)
n <- 6

sapply(s, function(i) sample(c(rep(1, i), rep(0, n - i))))
#      [,1] [,2] [,3]
# [1,]    0    1    1
# [2,]    1    0    0
# [3,]    0    1    0
# [4,]    0    0    1
# [5,]    0    0    0
# [6,]    0    0    1

【讨论】:

  • 也许将n 传递到函数中,因此它是明确的来自哪里,并且不依赖于封闭环境? sapply(s, FUN=function(s,n){...}, n=n)
  • 抱歉,我最初的问题不够清楚。行总和始终为 1。我对其进行了编辑。无论如何,谢谢您的意见。我会考虑一下,看看我是否能想出适合我需要的东西。
【解决方案2】:
s <- c(1,2,3)
result = matrix(0, nrow = max(s), ncol = length(s))
for (i in seq_along(s)) result[1:s[i], i] = 1
result
#      [,1] [,2] [,3]
# [1,]    1    1    1
# [2,]    0    1    1
# [3,]    0    0    1

将行和保持为 1

s <- c(1,2,3)
result = matrix(0, nrow = sum(s), ncol = length(s))
result[cbind(1:sum(s), rep(seq_along(s), times = s))] = 1
result
#      [,1] [,2] [,3]
# [1,]    1    0    0
# [2,]    0    1    0
# [3,]    0    1    0
# [4,]    0    0    1
# [5,]    0    0    1
# [6,]    0    0    1

【讨论】:

  • 抱歉,我说的不够清楚。行总和始终为 1。我编辑了原始帖子。无论如何感谢您的意见。
【解决方案3】:
# Input:
s <- c(1,2,3)
# ...
set.seed(1) # For reproducibility
nr <- sum(s)
nc <- length(s)
mat <- matrix(0L, nrow = nr, ncol = nc)
mat[cbind(seq_len(nr), sample(rep(seq_len(nc), s)))] <- 1L

# Output:
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    0    1
[3,]    0    1    0
[4,]    0    0    1
[5,]    0    1    0
[6,]    0    0    1

【讨论】:

    猜你喜欢
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多