簡體   English   中英

向量化嵌套循環r

[英]Vectorize nested for loops r

我在嘗試向量化R中的嵌套for循環時遇到了一個問題。
基本上,程序在數據幀中查找特定的編碼值,在命名列表中找到該代碼,然后將值編碼的內容存儲在向量中。 最后,我將所有這些向量綁定在一起,以創建未編碼值的矩陣。 不過,我對函數式編程還是比較陌生,並且想以某種方式優化此過程,但是我無法弄清楚如何在沒有for循環的情況下使它正常工作!

rawdata是編碼值。 rawdata中的每一列都是一個問題,用於調查接受者。 看起來像這樣:

q1 q2 q3
a1 b1 c1
a2 b2 c2
a3 '' ''

datacodes是每個問題的列表和它們的可能的碼的數據幀。

請注意,a3不在q1的列表中。 碰巧有時候答案不在Codex中,所以我想保留功能,如果發生這種情況,則輸入代碼,而不是NA。 l是每個問題都是代碼和答案的命名列表的列表。 就像datacodes一樣,但是它是命名列表的列表,因此看起來像:

l = list(q1=list(a1=alpha,a2=beta), q2=list(b1=gamma,b2=delta)...) 

等等。 這是代碼:

#Checks each "cell" to see if the code is within the codex pertaining
# to the question asked, if it is, then the decoded value is stored
#if not, then the coded value is stored in the vector

for (column in 1:length(rawdata)){
  for (row in 1:length(rawdata$column1)){
    codex<-l[[colnames(rawdata)[i]]]
    code<-rawdata[[colnames(rawdata)[i]]][row]
    keys<-datacodes$data[[i]]$key
    if(code %in% keys){
      p[row]<-codex[[as.character(code)]]
    }
    else{
      p[row]<-code
      }
    }
  }
#tacks on each finished vector to form a matrix
decode<-cbind(decode,p)
}

輸出應該是這樣的:

q1    q2    q3
alpha gamma epsilon
beta  delta zeta
a3    ''    ''

通過刪除內部循環並使用match函數,這是一種可能的解決方案。 這將創建原始數據的副本,然后替換已定義列表“ l”中的匹配值。 由於它是一個命名列表,因此很容易檢索所需的值列表以進行替換。

rawdata<-read.table(header = TRUE, text="q1 q2 q3
a1 b2 c1
a2 b1 c2
a3 b1 ''")

l = list(q1=list(a1="alpha",a2="beta"), q2=list(b1="gamma",b2="delta"), q3=list(c1="epsilon",c2="zeta")) 

#make copy of data to update
answer<-rawdata

#loop through the question columns in rawdata
for (n in names(rawdata)) {
   #match the answer to the provide list
   mat<-match(rawdata[[n]], names(l[[n]]))

   #convert from factors to character type
   answer[[n]]<-as.character(answer[[n]])

   #Remove any NA answers and 
   #update the rows and column in the copy of the original data
   answer[[n]][which(!is.na(mat))]<- unlist(l[[n]][mat[!is.na(mat)]])
}
answer

     q1    q2      q3
1 alpha delta epsilon
2  beta gamma    zeta
3    a3 gamma        

如果根據答案的數量與問題的數量進行比較,則可以確定績效提高的程度。

注意:我確實更新了示例數據以改進測試。

暫無
暫無

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

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