我有以下矩阵“ myMatrix2”:
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[4,] 1 2 3
现在,我想编写一个函数,将以值1开头的所有行放入新矩阵中。
这是我想出的:
retrieverows_2 <- function(matrixold, y=1){
matrixnew <<- matrix()
while(y<=nrow(matrixold)){
if(matrixold[y,1]==1){
matrixnew <<- rbind(matrixold[y,])
}
y <- y+1
}
}
现在的问题是,它似乎覆盖了新矩阵的行,因此它仅返回初始矩阵的最后一行,如下所示:
[,1] [,2] [,3]
[1,] 1 2 3
我期望的结果是:
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 1 2 3
也许有人可以向我解释为什么rbind()
覆盖新矩阵的行吗?
答案 0 :(得分:2)
对于这样的简单情况,您不应迭代添加/ public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
SimpleDateFormat sdf1234 = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
String abs12 = value.getExpiryData();
Date todayDate = new Date();
try {
Date testDate1 = sdf1234.parse(abs12);
if(testDate1.compareTo(todayDate) <0){// expired
dataSnapshot1.getRef().removeValue();
}
else if(testDate1.compareTo(todayDate)==0){// both date are same
if(testDate1.getTime() == todayDate.getTime() || testDate1.getTime() < todayDate.getTime())
{// expired
dataSnapshot1.getRef().removeValue();
}
else
{//expired
//Toast.makeText(getApplicationContext(),"Successful praju ",Toast.LENGTH_SHORT).show();
}
}else{//expired
// Toast.makeText(getApplicationContext(),"Successful praju ",Toast.LENGTH_SHORT).show();
}
} }
。而是使用子集:
rbind
至于为什么您的代码只返回一行,所以您每次都在重写m <- matrix(c(1,2,3,1,4,5,6,2,7,8,9,3), nrow = 4, ncol = 3)
newmat <- m[which(m[,1] == 1),]
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 1 2 3
。您需要创建一个计数器来跟踪新行。像
newmatrix
但是所有这些都应该替换为子集。