【发布时间】:2016-10-05 12:20:42
【问题描述】:
我有一组数据和一个循环,其中包含数据集的大量计算,其中该组的各个组件被分成一个子集并一个一个地循环。但是,我首先需要能够对整个原始数据集执行相同的计算。
对于一个名为 masterdata 的虚构数据集,它包含 3 个组件(D1 列)和许多变量 (X2-X10):
# masterdata
# D1 X2 X3 X4 X5 X6 X7 X8 X9 X10
# A NA NA NA NA NA NA NA NA NA
# B NA NA NA NA NA NA NA NA NA
# C NA NA NA NA NA NA NA NA NA
# B NA NA NA NA NA NA NA NA NA
# B NA NA NA NA NA NA NA NA NA
# C NA NA NA NA NA NA NA NA NA
# C NA NA NA NA NA NA NA NA NA
# A NA NA NA NA NA NA NA NA NA
# B NA NA NA NA NA NA NA NA NA
# A NA NA NA NA NA NA NA NA NA
有一个循环来拆分组件 A 的子集,执行计算,输出结果,然后对 B 和 C 重复此操作:
Component.List = c("A", "B", "C")
for(k in 1:length(Component.List)) {
subdata = subset(masterdata, D1 == Component.List[k])
# Numerous calculations performed on "subdata" within the loop
}
# End of loop
我要做的是最初对整个masterdata 执行相同的大量计算,然后开始循环遍历各个组件。
计算的部分输出是创建的两个向量被放置在执行循环之前创建的数据帧的第一列中:
# Prior to the start of the loop two frames below created
Components = 3 # In this example 3 components in column D1 - "A", "B", "C"
Result.Frame.V1 = as.data.frame(matrix(0, nrow = 200, ncol = Components))
Result.Frame.V2 = as.data.frame(matrix(0, nrow = 200, ncol = Components))
# Loop runs and contains all of the calculations and within the calculations the last two
# lines below place two vectors generated into the the kth columns of the frames.
Result.Frame.V1[,k] = V1.Result
Result.Frame.V2[,k] = V2.Result
# First run of the loop for "A" will place the outputs in the 1st columns
# Second run of the loop for "B" will place the outputs in the 2nd columns, etc.
# With the expansion to also calculate against the whole group, the above data frames
# would be expanded to an extra column that would hold the result vector for the whole
# masterdata run through the calculations
我最初的理论解决方案是为masterdata编写一次循环中的每个计算,然后进行上述循环,但是计算是数百行代码!
是否可以在 For 循环中加入一种计算原始数据的方法,然后继续循环遍历组件?
【问题讨论】:
-
为什么不把所有的计算都封装到一个单独的函数中,依次传递data.frames给它,
masterdata,ComponentA,ComponentB等等 -
不需要
for循环。按组件split(masterdata, masterdata$D1)将数据框拆分为列表,然后使用lapply/sapply对每个列表条目执行计算。使用do.call(rbind, ...)绑定任何生成的数据帧(如有必要)。 -
您希望从函数或数据帧中获取向量吗? e.i 1 行 vs 多行?
-
@JonnoBourne 在计算中,有从中输出的向量和数据帧。