我想创建的数据帧output
从数据框中input
通过运行给出了两个变量多个场景中的Rx
和y
。列output
是所有值的列的总和value
那里有xcol < x & ycol < y
。
input =
xcol ycol value
1 5 4
2 6 9
3 7 8
4 9 7
5 14 8
和
output=
x y results
2 5 0
2 10 4
2 15 35
...
6 5 0
6 10 27
6 15 35
我的代码目前是这样的:
for (x in 2:6) {
if (x%% 2){
next
}
for (y in 5:15) {
if (y %% 5){
next
}
print(x)
print(y)
print(sum(input$value[!is.na(input$xcol) & !is.na(input$ycol) & !is.na(input$value) &
input$xcol < x & input$ycol < y]))
}
}
应该有更好的方法来使用 lapply & sapply 替换这个嵌套循环并创建我认为的数据帧。我很感激任何帮助。
谢谢
这似乎更像是一个设计的,实验的,从某种意义上说,你在哪里迭代的不同可能值x
和y
。
xs <- 2:6
ys <- 5:15
eg <- expand.grid(x = xs, y = ys)
head(eg)
# x y
# 1 2 5
# 2 3 5
# 3 4 5
# 4 5 5
# 5 6 5
# 6 2 6
我认为您的%%
过滤应该在此之前/之前完成,因此:
xs <- xs[!xs %% 2]
ys <- ys[!ys %% 5]
eg <- expand.grid(x = xs, y = ys)
head(eg)
# x y
# 1 2 5
# 2 4 5
# 3 6 5
# 4 2 10
# 5 4 10
# 6 6 10
从这里,您可以遍历行:
eg$out <- sapply(seq_len(nrow(eg)), function(r) {
sum(input$value[ complete.cases(input) & input$xcol < eg$x[r] & input$ycol < eg$y[r] ])
})
eg
# x y out
# 1 2 5 0
# 2 4 5 0
# 3 6 5 0
# 4 2 10 4
# 5 4 10 21
# 6 6 10 28
# 7 2 15 4
# 8 4 15 21
# 9 6 15 36
我认为你的output
变量有点偏离,因为“2,15”应该只包括input$value[1]
(x < 2
是限制因素)。(存在其他差异。)
无论您的实际索引逻辑如何,我都建议在双重for
或双重lapply
实现上使用这种方法。
注意:
这些命令在功能上与此等效input
:
complete.cases(input) # 1
complete.cases(input[c("xcol","ycol","value")]) # 2
!is.na(input$xcol) & !is.na(input$xcol) & !is.na(input$value) # 3
我使用了第一个,因为“代码高尔夫”,但如果您的实际input
data.frame 包含其他列,您可能更喜欢第二个更有选择性地选择哪些列需要非NA
值。
expand.grid
非常适合这种类型的扩展。但是,如果您正在查看明显更大的数据集(包括您的过滤是否比%%
优惠更复杂),那么它可能会有点昂贵,因为它必须data.frame
在内存中创建整个。Python 使用惰性迭代器在这里会很有用,在这种情况下,您可能更喜欢使用https://stackoverflow.com/a/36144255/3358272(github gist 中的扩展函数以及一些文档:https://gist.github。 com/r2evans/e5531cbab8cf421d14ed)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句