我无法将数据集扩展到每个变量的所有组合中。我们有一个数据集,该数据集包含许多Npoints
列,每个列iterate
本身都包含多个X,Y点。数据在Npoints
3和iterate
4时看起来像这样。
X1 Y1 X2 Y2 X3 Y3
20 1 30 1.5 50 0.9
21 1.1 33 1.3 45 1
19 0.9 28 1.6 53 1
25 1.2 31 1.4 55 1.2
我想按列扩展此数据文件,以便将函数应用于主要三列中的数据点的每个组合
foo <= function(x1, y1, x2, y2) {
y2 - x2*(y2 - y1)/(x2 - x1)
}
生成的文件应如下所示
x1 y1 x2 y2
20 1 30 1.5
21 1.1 33 1.3
19 0.9 28 1.6
25 1.2 31 1.4
20 1 50 0.9
21 1.1 45 1
19 0.9 53 1
25 1.2 55 1.2
30 1.5 50 0.9
33 1.3 45 1
28 1.6 53 1
31 1.4 55 1.2
似乎没有变种expand.grid
可以完成此操作,我可能必须根据Npoints
和创建一个函数iterate
,以便根据点数和迭代的数量来放大或缩小该函数,但是这对于函数来说有点复杂在这个阶段,似乎有很多效率低下的方法来完成此任务。
首先十分感谢。
#split the df into Npoints data frames
Npoints <- 3
l <- lapply(1:Npoints, function(i)df[,(2*i-1):(2*i)])
#cbind the data frames for each possible combination of Npoints
l1 <- apply(combn(Npoints, 2), 2, function(x)cbind(l[[x[1]]], l[[x[2]]]))
#rbind all
data.table::rbindlist(l1)
# X1 Y1 X2 Y2
# 1: 20 1.0 30 1.5
# 2: 21 1.1 33 1.3
# 3: 19 0.9 28 1.6
# 4: 25 1.2 31 1.4
# 5: 20 1.0 50 0.9
# 6: 21 1.1 45 1.0
# 7: 19 0.9 53 1.0
# 8: 25 1.2 55 1.2
# 9: 30 1.5 50 0.9
#10: 33 1.3 45 1.0
#11: 28 1.6 53 1.0
#12: 31 1.4 55 1.2
数据
structure(list(X1 = c(20L, 21L, 19L, 25L), Y1 = c(1, 1.1, 0.9,
1.2), X2 = c(30L, 33L, 28L, 31L), Y2 = c(1.5, 1.3, 1.6, 1.4),
X3 = c(50L, 45L, 53L, 55L), Y3 = c(0.9, 1, 1, 1.2)), .Names = c("X1",
"Y1", "X2", "Y2", "X3", "Y3"), class = "data.frame", row.names = c(NA,
-4L))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句