我正在尝试为矩阵(matx)中的每一列单独保存等于1的值的行号。对于每个其他对象,矩阵应包含0。它在某种程度上给了我一些稍微小一点的数字(开头的1个值较小,之后的两个和三个),但不是正确的值。原始矩阵的值仅为0和1。 我的尝试:
matx<-replicate(n=100,rbinom(n= 250, size=1, prob = 0.01))
maty<-apply(!matx, 2, function(x) ifelse(x==0,
which(x %in% 1),
x==0))
也尝试过:
maty<-apply(!matx, 2, function(x) ifelse(x>0, as.integer(rownames(matx)), 0))
第二次尝试只留下NA和0而不是行号。我很感谢你的帮助。
答案 0 :(得分:3)
假设@ akrun的解释是正确的(它也是我如何阅读问题)你也可以使用row
函数:
matx * row(matx)
# [,1] [,2] [,3] [,4] [,5]
# [1,] 0 1 0 0 0
# [2,] 0 0 2 0 0
# [3,] 3 3 3 0 0
# [4,] 4 4 0 0 0
# [5,] 5 0 0 5 0
# [6,] 6 6 6 0 0
# [7,] 0 0 0 7 0
# [8,] 8 0 8 8 0
# [9,] 9 9 9 9 0
# [10,] 0 0 0 10 0
答案 1 :(得分:1)
如果我们需要将'1s'(在二进制矩阵中)替换为相应的行号而保留'0',我们可以which
使用arr.ind=TRUE
获取行/非零数字的列索引,使用该索引将1s
替换为'ind'中的row index
列。在这里,我创建了一个'matx'(即'maty')的副本,以防需要原始矩阵。
maty <- matx
ind <- which(matx!=0, arr.ind=TRUE)
maty[ind] <- ind[,1]
maty
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 1 0 0 0
#[2,] 0 0 2 0 0
#[3,] 3 3 3 0 0
#[4,] 4 4 0 0 0
#[5,] 5 0 0 5 0
#[6,] 6 6 6 0 0
#[7,] 0 0 0 7 0
#[8,] 8 0 8 8 0
#[9,] 9 9 9 9 0
#[10,] 0 0 0 10 0
和原始矩阵
matx
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 1 0 0 0
#[2,] 0 0 1 0 0
#[3,] 1 1 1 0 0
#[4,] 1 1 0 0 0
#[5,] 1 0 0 1 0
#[6,] 1 1 1 0 0
#[7,] 0 0 0 1 0
#[8,] 1 0 1 1 0
#[9,] 1 1 1 1 0
#[10,] 0 0 0 1 0
注意:这也可以用于非数字元素
或@ eipi帖子中的base R
解决方案的apply
修改
apply(matx, 2,function(x) ifelse(x!=0, seq_along(x), 0) )
set.seed(24)
matx <- matrix(sample(0:1, 10*5, replace=TRUE), nrow=10)
答案 2 :(得分:1)
如果您的原始matx纯粹是0s和1s,那么这个显示工作:
maty <- matx * row(matx)
一个例子:
> matx # stealing from akrun
[,1] [,2] [,3] [,4] [,5]
[1,] 0 1 0 0 0
[2,] 0 0 1 0 0
[3,] 1 1 1 0 0
[4,] 1 1 0 0 0
[5,] 1 0 0 1 0
[6,] 1 1 1 0 0
[7,] 0 0 0 1 0
[8,] 1 0 1 1 0
[9,] 1 1 1 1 0
[10,] 0 0 0 1 0
> matx * row(matx)
[,1] [,2] [,3] [,4] [,5]
[1,] 0 1 0 0 0
[2,] 0 0 2 0 0
[3,] 3 3 3 0 0
[4,] 4 4 0 0 0
[5,] 5 0 0 5 0
[6,] 6 6 6 0 0
[7,] 0 0 0 7 0
[8,] 8 0 8 8 0
[9,] 9 9 9 9 0
[10,] 0 0 0 10 0
答案 3 :(得分:0)
以下是使用apply
:
library(zoo) # For index function
apply(matx, 2, function(x) ifelse(x==1, index(x), 0))