簡體   English   中英

如何在R中向量化此for循環

[英]How to vectorize this for loop in R

我在R方面沒有太多經驗。我有一個像這樣的for循環:

combination<-read.csv(choose.files())
rownames(n_weight)<-1:154
colnames(n_weight)<-rownames(n_weight)
for(i in 1:length(n_weight)){
  for(j in 1:length(n_weight)){
  if(i==j){
    n_weight[i,j]<-1
  }
}}

idex <- dim(combination)[1]   #idex is length 
m <- as.data.frame(matrix(0, ncol = idex, nrow = idex))
rownames(m) <- as.numeric(combination$FID)
colnames(m) <- rownames(m)



# n_weight: 154X154 matrix
# m: 23562*23562 matrix
# combination: data.frame with 23562 obs. 

for(i in 1:23562){
  for (j in 1:23562){
    if(n_weight[combination[i,]$PC,combination[j,]$PC]==1){
      if(n_weight[combination[i,]$RC,combination[j,]$RC]==1){
        m[i,j]<-1}
    }}}

這花費了太多時間。 有沒有辦法向量化這個循環? 謝謝!

試試看:

met_conditions <- ifelse(n_weight[combination$PC, combination$PC] == 1 & 
     n_weight[combination$RC, combination$RC] == 1, TRUE, FALSE)

m[met_conditions] <- 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM