我有一个i次j(ixj
)虚拟矩阵用于评估公司的事件,有i个日期和j个不同的公司。评级为[i,j]=1
且评分为0的日期。
我想创建一个列表,其中包含4个子列表(4个公司中的每个公司都有1个)。每个子列表都说明了特定公司的评级事件的行号。
这是我的代码:
r<-list(); i=1;j=2;
for(j in 1:4){
x<-list()
for(i in 100){
if(rating[i,j]!=0){
x<-c(x,i)
i=i+1
}
else{i=i+1}
}
r[[j]]<-x
j=j+1
}
它在某种程度上不起作用,我真的无法弄清楚bug的位置。 x子列表始终为空。有人可以帮忙吗?
非常感谢!
以下是评级矩阵示例:
rating<-matrix(data = 0, nrow = (100), ncol = 4, dimnames=list(c(1:100), c(1:4)));
rating[3,1]=1;rating[7,1]=1;rating[20,1]=1;rating[75,1]=1;
rating[8,2]=1;rating[40,2]=1;rating[50,2]=1;rating[78,2]=1;
rating[1,3]=1;rating[4,3]=1;rating[17,3]=1;rating[99,3]=1;
rating[10,4]=1;rating[20,4]=1;rating[30,4]=1;rating[90,4]=1;
答案 0 :(得分:3)
你可以试试这个:
set.seed(123)
m <- matrix(data = sample(c(0, 1), 16, replace = TRUE), ncol = 4,
dimnames = list(date = 1:4, company = letters[1:4]))
m
# company
# date a b c d
# 1 0 1 1 1
# 2 1 0 0 1
# 3 0 1 1 0
# 4 1 1 0 1
lapply(as.data.frame(m), function(x){
which(x == 1)
})
# $a
# [1] 2 4
#
# $b
# [1] 1 3 4
#
# $c
# [1] 1 3
#
# $d
# [1] 1 2 4
<强>更新强>
或者更紧凑(感谢@flodel!):
lapply(as.data.frame(m == 1), which)
答案 1 :(得分:0)
(留下for循环。)如果评级确实是一个矩阵,或者即使它是一个数据帧,那么为什么不使用rowSums:
r <- rowSums(rating) # accomplished the stated task more effectively.
# simple example:
> rating <- matrix( rbinom(100, 1,prob=.5), 10)
> rating
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 0 1 0 0 1 1 0 0 1
[2,] 1 0 0 0 0 0 0 1 1 1
[3,] 0 0 1 1 1 1 0 0 1 0
[4,] 1 0 0 0 1 1 0 0 0 1
[5,] 1 1 0 1 1 1 1 0 0 0
[6,] 1 1 1 0 1 1 1 0 1 0
[7,] 0 1 0 1 0 1 1 0 1 0
[8,] 0 1 0 0 1 1 0 1 1 0
[9,] 1 1 1 0 1 1 1 1 0 0
[10,] 0 1 0 0 1 0 0 1 0 1
> rowSums(rating)
[1] 5 4 5 4 6 7 5 5 7 4
> rowSums(as.data.frame(rating))
[1] 5 4 5 4 6 7 5 5 7 4
如果它需要是一个列表,那么只需在它周围包装as.list()。