在R中操纵子矩阵 [英] Manipulating sub matrices in R

查看:152
本文介绍了在R中操纵子矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Nh<-matrix(c(17,26,30,17,23, 17 ,24, 23), nrow=2, ncol=4); Nh
Sh<-matrix(c(8.290133, 6.241174, 6.096808, 7.4449672, 6.894924, 7.692115, 
             4.540521, 7.409122), nrow=2, ncol=4); Sh
NhSh<-as.matrix(Nh*Sh); NhSh
rh<-c( 0.70710678, 0.40824829, 0.28867513, 0.22360680, 0.18257419, 
       0.15430335, 0.13363062, 0.11785113, 0.10540926, 0.09534626); rh

pv <- c()
for (j in 1:2) {
  for (i in 1:4) {

    pv <- rbind(pv, NhSh[j,i]*rh)
  }
}
pv

row.names(pv) <- rep(c(1:2), each = 4)
lst<-lapply(split(seq_len(nrow(pv)), as.numeric(row.names(pv))), function(i) 
pv[i,])

data<-40
nlargest <- function(x, data) 
{
  res <- order(x)[seq_len(data)];
  pos <- arrayInd(res, dim(x), useNames = TRUE);
  list(values = pv[res], position = pos)
}
out <- lapply(lst, nlargest, data = 40)

在上面的代码中,是否有任何简便的方法可以对1:2中k的每个out $ k $$位置重复以下步骤?

In continuation of above code Is there any brief way of repeating the following steps for each out$’k’$position for k in 1:2?

s1<-c(1,1,1,1); ch<-c(5,7,10,5); C<-150; a<-out$'1'$position 
for (j in a[40:1, "row"] ) 
{
 s1[j] <- s1[j]+1;
 cost1 <- sum(ch*s1);
 if (cost1>=C) break
}
s1; cost1
#Output [1] 5 6 6 5  

#       [1] 152

我必须在$ k $位置获得2个"s"和"cost"值.我尝试过

I have to get 2 values for 's' and 'cost' for out$k$position. I tried

mat = replicate (2,{x = matrix(data = rep(NA, 80), ncol = 2)}); mat
for (k in 1:2)
{
  mat[,,k]<-out$'k'$position
}
mat

错误在mat [,,k]<-out $ k $ position:要替换的项目数不是替换长度的倍数

Error in mat[, , k] <- out$k$position :number of items to replace is not a multiple of replacement length

for (k in 1:2)
{
for (j in mat[,,k][40:1] ) {
  s[j] <- s[j]+1  
  cost <- sum(ch*s)
  if (cost>=C) break

}
}
s; cost

错误:s [j]<-s [j] + 1中的错误:下标分配中不允许使用NAs

Error : Error in s[j] <- s[j] + 1 : NAs are not allowed in subscripted assignments

请任何人帮助解决这些错误.

Please anyone help in resolving these errors.

推荐答案

我们可以通过遍历list来直接应用该函数.请注意,list的每个元素都是一个matrix

We could apply the function directly by looping over the list. Note that each element of the list is a matrix

sapply(lst, is.matrix)
#  1    2 
#TRUE TRUE 

因此,无需unlist并创建matrix

out <- lapply(lst, nlargest, data = 40)

-检查OP的结果

out1 <- nlargest(sub1, 40)
identical(out[[1]], out1)
#[1] TRUE

Update2

基于第二次更新,我们需要使用与"k"个元素相同的长度来初始化"cost"和"sl".在这里,我们将'sl'初始化为vectors

sl <- rep(list(c(1, 1, 1, 1)), 2)
C <- 150
cost <- numeric(2)
for (k in 1:2){

for (j in mat[,,k][40:1, 1] ) {
    sl[[k]][j] <- sl[[k]][j]+1  
    cost[k] <- sum(ch*sl[[k]])
    if (cost[k] >=C) break


    }
   }   


sl
#[[1]]
#[1] 5 7 6 4

#[[2]]
#[1] 6 5 5 7

cost
#[1] 154 150

这篇关于在R中操纵子矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆