向量化嵌套循环r

时间:2019-02-28 15:54:07

标签: r functional-programming vectorization named

在向量化R中的嵌套for循环时遇到了一个问题。
基本上,程序在数据帧中查找特定的编码值,在命名列表中找到该代码,然后将值编码的内容存储在向量中。最后,我将所有这些向量绑定在一起,以创建未编码值的矩阵。我对函数式编程还是比较陌生,并且想以某种方式优化此过程,但是我无法弄清楚如何在没有for循环的情况下使它正常工作!

原始数据是编码值。 rawdata中的每一列都是一个问题,用于调查接受者。看起来像这样:

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

数据代码是每个问题及其可能的代码列表的数据框架。

请注意,a3不在q1的列表中。碰巧有时候答案不在Codex中,所以我想保留功能,如果发生这种情况,则输入代码,而不是NA。 l 是列表,每个问题都是代码和答案的命名列表。它类似于数据代码,但它是命名列表的列表,因此看起来像:

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    ''    ''

1 个答案:

答案 0 :(得分:2)

有一个可能的解决方案,即删除内部循环并使用declare @begin datetime2 = getdate() - .1 declare @end datetime2 = getdate() + .1 select case when datepart(dw, @begin) in (2,3,4,5,6) and datepart(dw, @end) in (2,3,4,5,6) then rtrim(datediff(hour, @begin, @end)) + ' hours' else 'Weekend! Go Home!' end 函数。这将创建原始数据的副本,然后替换已定义列表“ l”中的匹配值。由于它是一个命名列表,因此很容易检索所需的值列表以进行替换。

match

如果根据答案的数量与问题的数量进行比较,可以确定绩效提高的程度。

注意:我确实更新了示例数据以改进测试。

相关问题