R 将频率向量转换为逻辑矩阵
我想将频率向量(即矩阵的R 将频率向量转换为逻辑矩阵,r,matrix,vector,R,Matrix,Vector,我想将频率向量(即矩阵的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
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
ssset.seed(523)
s#输入:
s行和总是1?什么决定了1的位置?@sindri_baldur是的,我在原始帖子中添加了它。@akrun Chance和总行和。所需的输出可以被视为一个多项式数据集,如果每一行正好有一个值1,其余的值为0。但是colsums应该等于s中的值。也许将n
传递到函数中,这样它就可以明确地知道从何而来,并且不依赖于封闭环境sapply(s,FUN=function(s,n){…},n=n)
对不起,我的第一个问题不够清楚。行和总是1。我编辑了它。谢谢你的意见。我会考虑一下,看看能不能想出符合我需要的东西。啊,对不起,我说得不够清楚。行和总是1。我编辑了原文。无论如何,谢谢你的意见。
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
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
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
# 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