我有一个矩阵,看起来像这样
myMatrix <- matrix(data = TRUE, nrow = 3, ncol = 3)
myMatrix[as.matrix(expand.grid(1:2, 1:2))] <- FALSE
myMatrix
[,1] [,2] [,3]
[1,] FALSE FALSE TRUE
[2,] FALSE FALSE TRUE
[3,] TRUE TRUE TRUE
我想得到一个列出所有行和列索引的数据框或矩阵,其中myMatrix
是TRUE
:
column row
1 3 1
2 3 2
3 1 3
4 2 3
5 3 3
我该怎么做?
答案 0 :(得分:3)
我们可以使用select p.billing_cycle_in_months, avg(t.days)
from (
select *,
datediff(day,transaction_settled_at, transaction_refunded_at) as days,
dense_rank() over (partition by signup_id order by transaction_settled_at asc) as rank
from transactions
) t
join signups s on s.signup_id = t.signup_id
join plans p on p.id = s.plan_id
where datediff(year,s.started_at, current_date) > 1 and t.rank = 1
group by p.billing_cycle_in_months
which
或使用which(myMatrix, arr.ind = TRUE)
并指定arrayInd
答案 1 :(得分:1)
我们可以使用row
和col
来获取矩阵中每个元素的行索引和列索引,并使用TRUE
的逻辑值对myMatrix
值进行子集化。
data.frame(column = col(myMatrix)[myMatrix], row = row(myMatrix)[myMatrix])